Tuesday, March 30, 2010


This talks about LINQ and gives you understanding difference btw IEnumerable<T>  and IQueryable<T> used in LINQ to SQL.

Expression Trees are datastructures, basically they (expression trees) are code sitting in memory as data. So why is that needed in the first place, to do such a thing where code needs to act as data?

• Everyone knows what happens to your code when you compile it; it is converted to MSIL right.
• Now as for data, it is not compiled into MSIL instead it stays in the memory.

So now I have a question for you,

What should I do if I do not want some code to be compiled into MSIL ?

Yep..We make the code as data (structure) in memory and it is not compiled to MSIL. Hurray...I think, I understood the need for Expression Trees.

Now one important feature, Lambda Expressions they are just anonymous methods (right), one thing which I did not notice at the start was that when we use a lambda expression what is actually happening.

Lambda Expression:

(string s,int a,int b) => s.Substring(a,b)

The above example is pretty straight forward it represents a method which takes in 3 inputs and returns a string. Now we have "Func" keyword that represents a generic delegate in C#. So now when I write the same code above like this (it is the same):

Func genericDelegateCode = (string s, int a, int b) => s.Substring (a, b);

So what I had missed before was that the lambda expressions actually generate an anonymous delegate, not an anonymous method. You know that very clearly from the above example. So I will change the above code a bit to show that lambda expression is actually an anonymous delegate.

Func genericDelegateCode = delegate (string s, int a, int b) {return s.Substring (a, b) ;}

Now how do I put this, lambda expression in memory, simple by making it an expression tree (which is nothing but code as data in memory).

Note: “data” is highlighted above to remind you that now your Lambda expression is now in memory as an Expression Tree and will not be compiled to MSIL as it does usually.

So your code is now in memory and can be compiled using compile() keyword on the expression keyword “data” which then generates the method in MSIL, and you can Invoke it and pass the parameters.

String output = data.Compile().Invoke(“Balakrishna”,2,3) ;

Now, all this entire article is doing is making you understand what Expression Trees are. Expression Trees is a very advanced topic, and is mostly used with LINQ flavors other than LINQ to Objects.

My future posts will get deeper, and all this dynamic runtime generation of code will make much better sense. I will try to include the below topics in future posts

• When to use Expression Trees, and why to use them.
• Explain the Expressions Trees API library, and how to manually create trees using them.

Hope you understood the basic concept...What Expression Trees are Expressing.

No comments:

Post a Comment