Created
August 16, 2012 03:17
-
-
Save hyrmn/3366176 to your computer and use it in GitHub Desktop.
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
public static class Guard | |
{ | |
public static void EnsureNotNull<TProperty>(Expression<Func<TProperty>> propertyName) | |
{ | |
var expression = GetMemberExpression(propertyName); | |
var value = GetValue(expression); | |
if (ReferenceEquals(null, value)) | |
{ | |
throw new ArgumentNullException(expression.Member.Name); | |
} | |
} | |
public static void EnsureNotNullOrEmpty(Expression<Func<string>> property) | |
{ | |
var expression = GetMemberExpression(property); | |
var value = GetValue(expression) as string; | |
if (string.IsNullOrEmpty(value)) | |
{ | |
throw new ArgumentNullException(expression.Member.Name); | |
} | |
} | |
private static MemberExpression GetMemberExpression<TProperty>(Expression<Func<TProperty>> property) | |
{ | |
var lambda = (LambdaExpression)property; | |
var unaryExpression = lambda.Body as UnaryExpression; | |
return (MemberExpression)(unaryExpression != null ? unaryExpression.Operand : lambda.Body); | |
} | |
private static object GetValue(MemberExpression memberExpression) | |
{ | |
var constantExpression = memberExpression.Expression as ConstantExpression; | |
if (constantExpression != null) | |
{ | |
var type = constantExpression.Value.GetType(); | |
var fieldInfo = type.GetField(memberExpression.Member.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); | |
if (fieldInfo != null) | |
{ | |
return fieldInfo.GetValue(constantExpression.Value); | |
} | |
var propertyInfo = type.GetProperty( | |
memberExpression.Member.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); | |
if (propertyInfo != null) | |
{ | |
return propertyInfo.GetValue(constantExpression.Value, null); | |
} | |
} | |
//// Otherwise, convert the argument subexpression to type object, | |
//// make a lambda out of it, compile it, and invoke it to get the value | |
Expression<Func<object>> lambdaExpression = Expression.Lambda<Func<object>>(Expression.Convert(memberExpression, typeof(object))); | |
return lambdaExpression.Compile()(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment