I am trying to write a generic function that takes a MemberExpression and an object and returns the value of the Property defined in the member expression.
Here's an example of the code to get the Property name.
public static TProperty GetPropertyName<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression, TModel model)
{
if (expression.Body is MemberExpression)
{
return ((MemberExpression)expression.Body).Member.Name;
}
else
{
var op = ((UnaryExpression)expression.Body).Operand;
return ((MemberExpression)op).Member.Name;
}
}
But I want to retrieve the value of the property from the model:
public static string GetPropertyValue<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression, TModel model)
{
if (expression.Body is MemberExpression)
{
// how do I apply the expression.Body to get the value of the property from model??
}
else
{
var op = ((UnaryExpression)expression.Body).Operand;
return ((MemberExpression)op).Member.Name;
}
}
The way I call this function is:
GetPropertyValue<ObjectModel,bool>(m => m.somebool, m);
MemberExpression
refers toMemberInfo
, which will bePropertyInfo
in case of property expression:Besides, it is more natural to swap parameters (first is
model
, second is expression). As a side effect, this allows compiler to infer type arguments: