Why are expression trees safer than reflection?

.net expression-trees reflection

Question

In this answer to the question of the fastest way to determine if a property contains a given attribute, user Darin Dimitrov posited that expression trees are safer than reflection. Is this true, and if so, why is it true?

Accepted Answer

Because when you search for your field (as in that question) you use string representation "Id". Once it is changed your reflection will collapse.

What Darin suggests is static typing:

Expression<Func<Program, int>> expression = p => p.Id;

You see that? This is interesting, but not well-known feature of C# 4.0 compiler: automatically build expression tree from lambda expression and cast it to Expression<T>. So then later you can traverse it and get MemberInfo of Id. But it is not as universal as Reflection because you can't search by string.


Popular Answer

The question as it is stated is why is expression trees safer then reflection.

The answer is that they are both using reflection.

Edit to clarify - MemberInfo.GetCustomAttributes is a reflection call.

http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.getcustomattributes(VS.71).aspx




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why