1

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.

Alex
  • 14,338
  • 5
  • 41
  • 59
  • possible duplicate of [Get the property name used in a Lambda Expression in .NET 3.5](http://stackoverflow.com/questions/3269518/get-the-property-name-used-in-a-lambda-expression-in-net-3-5) – Carlos G. Jun 01 '14 at 08:24

3 Answers3

6
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"
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • Thats shorter - if he only has to deal with MemberExpressions. – Arthur Jul 14 '10 at 13:31
  • If you want to statically define the propertyName:static readonly string SomethingProperty = GetMemberName(() => default(MyClass).Something); Also, you might want to disable warning 1720 so that the null use is not checked – sthiers Jun 12 '13 at 08:35
1

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

Arthur
  • 7,939
  • 3
  • 29
  • 46
0

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

DanP
  • 6,310
  • 4
  • 40
  • 68