Reputation: 14618
I have an expression, passed to a function, that looks something like this:
x=>x.SomeField
I want somehow to get to the name of this field, the "SomeField", to be accessible for me as a string. I realize that it's possible to call myExpression.ToString(), and then parse the string, but I want a more solid, faster approach.
Upvotes: 1
Views: 704
Reputation: 292465
public string GetMemberName<T>(Expression<Func<T>> expr)
{
var memberExpr = expr.Body as MemberExpression;
if (memberExpr == null)
throw new ArgumentException("Expression body must be a MemberExpression");
return memberExpr.Member.Name;
}
...
MyClass x = /* whatever */;
string name = GetMemberName(() => x.Something); // returns "Something"
Upvotes: 6
Reputation: 6478
I've used some of the helpers available in the ncommon framework to accomplish this. Specifically, you'd be interested in the classes in the Expressions namespace
Upvotes: 0
Reputation: 8129
You have to implement a expression tree visitor
http://msdn.microsoft.com/en-us/library/bb882521(VS.90).aspx
You put your eval code in the MemberAccessExpression visit
Upvotes: 1