Skip to content

Instantly share code, notes, and snippets.

@euyuil
Created July 4, 2014 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save euyuil/39cdb0a79711489dbce5 to your computer and use it in GitHub Desktop.
Save euyuil/39cdb0a79711489dbce5 to your computer and use it in GitHub Desktop.
C#: check null arguments in an elegant way
// Copied from:
// http://www.minddriven.de/index.php/technology/dot-net/c-sharp/efficient-expression-values
public static class Guard
{
public static void AssertNotNull<T>(Expression<Func<T>> selector)
{
var memberSelector = (MemberExpression)selector.Body;
var constantSelector = (ConstantExpression)memberSelector.Expression;
var value = ((FieldInfo)memberSelector.Member).GetValue(constantSelector.Value);
if (value == null)
{
var name = ((MemberExpression)selector.Body).Member.Name;
throw new ArgumentNullException(name);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment