Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExpressionHelper.GetExpressionText(LambdaExpression) alternative

Is there .NET Framework alternative to ExpressionHelper.GetExpressionText(LambdaExpression)? I need it in some of the projects that cannot reference System.Web.Mvc.

I understand that one of the possibilities is to write my own implementation of GetExpressionText(LambdaExpression) method but I don't want to do it. My target is to re-use already existing .NET Framework code.

like image 906
Volodymyr Usarskyy Avatar asked Nov 10 '11 12:11

Volodymyr Usarskyy


1 Answers

Implementing that method yourself is quite easy:

string GetPropertyName(LambdaExpression expression)
{
    var body = (MemberExpression)expression.Body;
    return body.Member.Name;
}

If the passed-in lambda is not MemberExpression, it will throw an exception (although you might want a more descriptive exception).

If you want to call the method directly like GetPropertyName(x => x.ID), you would need to somehow know what type x is. One way is a type parameter:

string GetPropertyName<T>(Expression<Func<T, object>> expression)
{
    var body = (MemberExpression)expression.Body;
    return body.Member.Name;
}

But this would mean you have to specify it explicitly:

GetPropertyName<Foo>(f => f.Id)
like image 178
svick Avatar answered Oct 03 '22 21:10

svick