Q:

How to get property name from expression

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

And function Exec wich accept expression:
void Exec<T>(Expression<Func<T, object>> expression)
{
}

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

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

A:

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);
    // ...
}

