Biscuits wrote about property (or field) selectors... There are two uses for these: one (the one he spoke about) to get the name of the field/property.
How to do it?
Given:
Expression<Func<Foo, int>> expression = x => x.Something;
You do:
string name = ((MemberExpression)expression.Body).Member.Name;
as written by others, in C# 6.0 this will become nearly useless thanks to nameof()
(that in general is faster because it's done at compile time instead that at runtime) and in C# 5.0 partially useless thanks to [CallerMemberName]
.
The second use is that, by passing an Expression<>
that is a "getter" (a function that given an object returns the value of something) to a method, the method can "build" a "setter".
Func<Foo, int> getter = expression.Compile();
var parameter = Expression.Parameter(expression.ReturnType);
Action<Foo, int> setter = Expression.Lambda<Action<Foo, int>>(
Expression.Assign(expression.Body, parameter ),
new[] { expression.Parameters[0], parameter }).Compile();
Foo foo = new Foo();
setter(foo, 5); // Example of use of the setter
int value = getter(foo); // Example of use of the getter
If you have to use a single time the setter, this is quite slower than using directly reflection (because the Expression
s must be built, then compiled and and so on, and in the building and compiling (but not in the using) of the Expression
there is use of reflection). But if you need to use many times the getter/setter, then it become faster (if you "cache" them), because the use of a getter/setter built in this way is nearly as much fast as accessing the property/field directly (the slow part is in the creation of the getter/setter)