I am using this code to set the value of a property via reflection :
public static void Set<T>(this T target, Expression<Func<T, object>> memberLamda, object value)
{
var memberSelectorExpression = memberLamda.Body as MemberExpression;
if (memberSelectorExpression != null)
{
var property = memberSelectorExpression.Member as PropertyInfo;
if (property != null)
{
property.SetValue(target, value, null);
}
}
}
But for some reason when I do :
myObject.Set(x=>x.ID, 1);
Where ID is of type int, I can see that memberSelectorExpression is null. However I have no issue with properties of a reference type.
I am not very familiar yet with expression trees, what I am doing wrong ?
The solution is to use the following signature :
To make sure a MemberExpression is correctly inferred. The "object" generic constraint is not specific enough.
The thing to be aware of is that your expression body will most likely be wrapped in a Convert expression, representing the fact that your property is being implicitly cast as an object. So you'll probably need code something like this in your Setmethod.