Sunday, December 16, 2007

Expression Trees

Hi

C# 3.0 introduced Lambda Expressions.
These are one of the building blocks of the LINQ.
Expression is a syntactic feature. uses the anonymous methods and the delegates (generic delegates).
It is a simplified syntax over using the generic delegates.

The general form of a Lambda Expression is

parms => function body

Consider following example.

p => ++p;

This Lambda Expression translates to

Func <<int,int>> incr = delegate (int p)
{
return ++p;
}

One good thing about these Lambda expressions is that one can tell compiler to generate an expression tree for a Lambda expression instead of a IL method ( in above example the Func delegate tells the compiler to generate the IL method).

Above expression can be rewritten as follows

Expression<<<<Func<<int,int>>>> exprIncr =
delegate (int p)
{
return ++p;
}

or

Expression<<<<Func<<int,int>>>> exprIncr = p=> ++p;

both code snippets above are same.

Expression trees are nothing but a binary tree which represents an expression. ( something like a tree for an arithmetic expression like a+b).

Following article goes in depth for expression trees.
http://courseweb.sp.cs.cmu.edu/~cs200/lecture18/lecture18.html.

Following post gives an overview of Lambda expressions and there genesis starting from .Net 1.0 delegates.

http://www.interact-sw.co.uk/iangblog/2005/09/30/expressiontrees


Thanks

No comments: