Search code examples
c#linqlambdaexpression-trees

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)

Solution

  • 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);