Alex
Alex

Reputation: 14618

How can I get the name of the field from an expression?

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

Answers (3)

Thomas Levesque
Thomas Levesque

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

DanP
DanP

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

Arthur
Arthur

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

Related Questions