Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are expression trees safer than reflection?

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?

like image 668
Charles Y. Avatar asked Nov 11 '10 20:11

Charles Y.


People also ask

Why do we use expression trees?

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.

What is the use of expression tree in C#?

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.


2 Answers

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.

like image 161
Andrey Avatar answered Oct 01 '22 10:10

Andrey


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

like image 40
asawyer Avatar answered Oct 01 '22 12:10

asawyer