Dear Gods of Reflection
I would like to have a generic GetValue
method that can return the following property values given the following
The problem is here:
if (response != null)
{
var expr = (MemberExpression)propertyExpression.Body;
var prop = (PropertyInfo)expr.Member;
return (T)prop.GetValue(response);
}
This only works if your expression references a property directly, otherwise propertyExpression.Body
will not be a MemberExpression
and you'll get a run-time cast error. The three that don't work do not reference a property directly - the first two reverence a method on top of a property (the indexer) and the last references a nested property.
Since all you want is the value of the expression, though, I think you can just do:
if (response != null)
{
Func<TEntity, T> func = propertyExpression.Compile();
return func(response);
}
If you intended to do other things with the expression (like get the name of the property), then you'll need to decide if you want to support expressions that don't reference a property directly and add handlers for that.
You can do it simply by Executing your Lambda expression:
if (response != null)
{
return propertyExpression.Compile().Invoke(response);
}