Skip to content

Instantly share code, notes, and snippets.

@Mrnikbobjeff
Created February 19, 2020 11:28
Show Gist options
  • Save Mrnikbobjeff/9f5ec4110f64aa7d02fbefcaaacc2285 to your computer and use it in GitHub Desktop.
Save Mrnikbobjeff/9f5ec4110f64aa7d02fbefcaaacc2285 to your computer and use it in GitHub Desktop.
internal class NoReturn<TReturn, TException> where TException : Exception
{
static NoReturn()
{
bool GetCorrectConstructor(ParameterInfo[] parameters) => parameters.Length == 1 && parameters[0].ParameterType == typeof(string);
var constructors = typeof(TException).GetConstructors();
var target = Expression.Label();
var constructor = constructors.Single(c => GetCorrectConstructor(c.GetParameters()));
var messageExpression = Expression.Parameter(typeof(string), "message");
var newException = Expression.New(constructor, messageExpression);
var throwExpression = Expression.Throw(newException, typeof(TReturn));
var retExp = Expression.Return(target, Expression.Default(typeof(TReturn)));
var block = Expression.Block(throwExpression, retExp);
ThrowDelegate = Expression.Lambda<Func<string, TReturn>>(throwExpression, messageExpression).Compile();
}
static Func<string, TReturn> ThrowDelegate;
internal TReturn Throw(string message)
{
return ThrowDelegate(message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment