Expression Tree + Reflection + C# 3.5
I've been trying to do something like this since C# 1.1.
Tonight I got to do it:
SomeCode.DoSomethingInProperty(cust => cust.Orders);
My problem has always been that I couldn't (using delegates before) get what property you want to use.
I could resort to reflection trickery and use the string property, but that's just not Refactoring friendly, now is it?
Today I learned how to it (using this article as reference: http://blog.naxsoft.com/archives/488/reflection-on-c-35). Here it goes:
public string PropertyBeingAssigned(Expression<Func<T, object>> property)
{ if (!(property.Body is MemberBLOCKED EXPRESSION)
throw new InvalidOperationException(
"Wrong type of Expression. This method only takes the property you're assigning the elements to.");
var member = (MemberExpression) property.Body;
var name = member.Member.Name;
return name;
}
Conclusion
As much as people say that the new C# is just syntatic sugar, I couldn't disagree more. The new features enable scenarios that once we only dreamt of.
What exciting times to be a .Net developer!!!
Edit
PS: Apparently Community server blocks the word MemberExpression for some reason. Just get it fixed in the "if (!property.Body" code