Created
July 4, 2014 08:13
-
-
Save euyuil/39cdb0a79711489dbce5 to your computer and use it in GitHub Desktop.
C#: check null arguments in an elegant way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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