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?
When you want to have a richer interaction, you need to use Expression Trees. Expression Trees represent code as a structure that you can examine, modify, or execute. These tools give you the power to manipulate code during run time. You can write code that examines running algorithms, or injects new capabilities.
Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y . You can compile and run code represented by expression trees.
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With