Expression trees are great...

Have you ever wanted to be able to do something like this in
C#?



string propertyName = GetName(MyClass.MyProperty);



Well I have, in fact I've wanted the ability to do this since
Version 1 of the .Net Framework, and now with C# 3.0 we finally
can!



First off, check out the original blog post here -
Symbols in C# 3.0
by Jafar Husain - it's a
clever (and once I thought about, plainly obvious) use of extension
methods and expression trees.


public static class SymbolExtensions
{
public static string GetPropertySymbol(this T obj, Expression<>> expr)
{
return ((System.Linq.Expressions.MemberExpression) (((System.Linq.Expressions.LambdaExpression)(expr)).Body)).Member.Name;
}
}


Usage requires a lambda, but that's not to painful, here's example
usage:


MyClass o;
//...
string propertyName = this.GetPropertySymbol(o => o.MyProperty)


The beauty of this is that refactoring is entirely painless, you
don't need to spend time reviewing all the optional string
replacements that resharper may have found in case you haven't
mirrored a property or method name change correctly... it also
looks like it could offer some nice usability improvements to some
unit testing scenarios (nothing worse then unit tests that don't
seamlessly refactor with your code).



I wonder what other ideas are floating around for expression trees
at the moment (outside of the obvious querying concepts) ?
Written on March 6, 2007