Welcome to Manicprogrammer Sign in | Join | Help

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

Published Wednesday, July 09, 2008 8:47 PM by heynemann
Filed under ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Expression Tree + Reflection + C# 3.5

Sunday, July 13, 2008 1:25 PM by Srihari

Hi Bernardo,

Nice point.

Also, there is a little extra blank lines in between.

Srihari

http://sriharik.blogspot.com

# How To Get A Property Name Using Lambda Expression in C# 3.0

Thursday, April 02, 2009 8:01 AM by Smallfish

During development of WPF application using M-V-VM design pattern (by Josh Smith on MSDN Mag.) I came


Enter the text you see in the image:

Leave a Comment

(required) 
required 
(required)