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

LINQ to SQL

Hi

One of the cool features of C# 3.0 is the LINQ.
This technology has the capability of changing the way tiered applications are written.

This is a great article from Microsoft this topic.
http://msdn2.microsoft.com/en-us/library/bb425822.aspx

Thanks

Saturday, December 15, 2007

Object Initializers in C# 3.0

Hi

C# 3.0 introduced something called as object initializers.

Consider following class

class Person
{
public int Age;
public string Name;
.....
}

One can instantiate this class as

Person firstPerson = new Person();
firstPerson.Age =10;
firstPerson.Name = "Bal";

We can also use the parametrized constructors for initializing attributes of a class.

With C# 3.0 we can create the Person object as

Person secondPerson = new Person{ Age = 10, Name ="Bandu" };

This is not same as creating the object and setting its values.

The expression is evaluated right to left and hence a temporary object is created which is finally assigned to the secondPerson.

One good thing about this expression is this is an atomic expression.
Means we don't have to specify any lock kind of construct when using this in multi threaded programs.


Thanks