Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get property name from expression

Tags:

c#

linq

I have class Test:

class Test
{
    public int Id {get;set;}
    public string Name {get;set;}
}

And function Exec which accepts expression:

void Exec<T>(Expression<Func<T, object>> expression)
{
}

...
Exec<Test>(t => t.Id);

How can I get the property name used in expression? In the code above this should be Id.

like image 305
alexmac Avatar asked Nov 11 '13 09:11

alexmac


1 Answers

Something like:

private static string GetMemberName(Expression expression)
{
    switch(expression.NodeType)
    {
        case ExpressionType.MemberAccess:
            return ((MemberExpression)expression).Member.Name;
        case ExpressionType.Convert:
            return GetMemberName(((UnaryExpression)expression).Operand);
        default:
            throw new NotSupportedException(expression.NodeType.ToString());
    }
}

with:

public void Exec<T>(Expression<Func<T, object>> expression)
{
    string name = GetMemberName(expression.Body);
    // ...
}
like image 122
Marc Gravell Avatar answered Sep 28 '22 15:09

Marc Gravell