zigzag
zigzag

Reputation: 627

Return value of property based on property name

How do I build expression tree in C# that returns value of a property based on the name of the property

Func<Foo, long> getValue(string propertyName)
{
    // i think that the beginning of the expression tree would look like this
    // but i'm not sure this is correct
    var inputParameter = Expression.Parameter(typeof(Foo));
    var desiredProperty = typeof(Foo).GetProperty(propertyName);
    var valueOfProperty = Expression.Property(inputParameter, desiredProperty);
    // ... ???   todo: expression that returns value
}

Call to this function looks like this which is part of another expression that is passed to Linq's Select method:

value = getValue("Bar").Invoke(FooInstance)

Upvotes: 0

Views: 84

Answers (1)

user2160375
user2160375

Reputation:

Should be enough:

var lambda = Expression.Lambda<Func<Foo, long>>(valueOfProperty, inputParameter);
return lambda.Compile();

Anyway - what's the purpose for building Expression when you could get value directly via reflection?

return someFoo => (long)desiredProperty.GetValue(someFoo);

Upvotes: 1

Related Questions