If you know the type "bar", you can do this (I reuse a few bits from the response to the codecase):
static void Main(string[] args) { var bar = new Bar(); bar.Foo = "Hello, Zap"; Zap(() => bar.Foo); Console.ReadLine(); } private class Bar { public String Foo { get; set; } } public static void Zap<T>(Expression<Func<T>> source) { var body = source.Body as MemberExpression; Bar test = Expression.Lambda<Func<Bar>>(body.Expression).Compile()(); Console.WriteLine(test.Foo); }
In most cases, you can find an expression representing your object in the expression tree, and then compile and execute that expression and get the object (but by the way, this is not a very fast operation). So, the bit you were missing is the Compile () method. You can find a little more information here: A practical guide. Run expression trees .
In this code, I assume that you always pass an expression like "() => object.Member". For a real-world scenario, you need to either analyze that you have an expression that you need (for example, just throw an exception if it is not MemberExpression). Or use ExpressionVisitor, which is quite complex.
I recently answered a very similar question: How do I subscribe to an object event inside an expression tree?
source share