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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With