Created
May 3, 2013 16:49
-
-
Save hanson-andrew/5511098 to your computer and use it in GitHub Desktop.
My implementation of an expression to property name converter. I use it to pull property names in a type-safe way. Usage: public void WhatProperty<T>(Expression<Func<T,object>> expr)
{ string name = GetPropertyName(expr);
}
This file contains hidden or 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
| string GetPropertyName(Expression e) | |
| { | |
| var lambdaExpression = e as LambdaExpression; | |
| if (lambdaExpression != null) | |
| { | |
| return GetPropertyName(lambdaExpression.Body); | |
| } | |
| var unaryExpression = e as UnaryExpression; | |
| if (unaryExpression != null) | |
| { | |
| return GetPropertyName(unaryExpression.Operand); | |
| } | |
| var memberExpression = e as MemberExpression; | |
| if (memberExpression != null) | |
| { | |
| return memberExpression.Member.Name; | |
| } | |
| throw new NotSupportedException(String.Format("Invalid Expression: {0}.", e.ToString())); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment