Created
October 19, 2012 09:05
-
-
Save cairey/3917077 to your computer and use it in GitHub Desktop.
Literal of an expression at runtime. Handy for property change notifications i.e Literal.Of(() => MyProperty)
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 Literal | |
{ | |
private static string GetMemberName(Expression expression) | |
{ | |
switch (expression.NodeType) | |
{ | |
case ExpressionType.MemberAccess: | |
var memberExpression = (MemberExpression)expression; | |
var supername = GetMemberName(memberExpression.Expression); | |
if (String.IsNullOrEmpty(supername)) | |
return memberExpression.Member.Name; | |
return String.Concat(supername, '.', memberExpression.Member.Name); | |
case ExpressionType.Call: | |
var callExpression = (MethodCallExpression)expression; | |
return callExpression.Method.Name; | |
case ExpressionType.Convert: | |
var unaryExpression = (UnaryExpression)expression; | |
return GetMemberName(unaryExpression.Operand); | |
case ExpressionType.Constant: | |
case ExpressionType.Parameter: | |
return String.Empty; | |
default: | |
throw new ArgumentException("The expression is not a member access or method call expression"); | |
} | |
} | |
public static string Of<T>(Expression<Func<T>> expression) | |
{ | |
return GetMemberName(expression.Body); | |
} | |
public static string Of(Expression<Action> expression) | |
{ | |
return GetMemberName(expression.Body); | |
} | |
public static string Of<T>() | |
{ | |
return typeof(T).Name; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment