Skip to content

Instantly share code, notes, and snippets.

@jbrestan
Created February 26, 2015 20:29
Show Gist options
  • Save jbrestan/b028f156090e3b633da2 to your computer and use it in GitHub Desktop.
Save jbrestan/b028f156090e3b633da2 to your computer and use it in GitHub Desktop.
NotNull runtime guard
public static class Ensure
{
public static TValue NotNull<TValue>(Expression<Func<TValue>> parameterExpression)
{
var possibleNull = parameterExpression.Compile().Invoke();
if (possibleNull == null)
{
var paramName = GetVariableName(parameterExpression);
throw new ArgumentNullException(paramName);
}
return possibleNull;
}
private static string GetVariableName<TValue>(Expression<Func<TValue>> parameterExpression)
{
var body = (MemberExpression) parameterExpression.Body;
return body.Member.Name;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment