Pages

Showing posts with label Dot Net Framework. Show all posts
Showing posts with label Dot Net Framework. Show all posts

Sunday, June 21, 2009

Lambda Expression Tree

Lambda expression is parsed as tree under the hood. The lambda expression is parsed and stored as tree-shaped structure. Each node in the expression tree is represented as expression. System.Linq.Expressions.Expression class contains static factory methods that can be used to build and manipulate expression tree. The following figure shows how a simple expression is parsed and represented.

image

As the above figure shows, the expression is represented with two parameters: Body and Parameters. We had two parameters in the image above. Each parameter is of type Expression (ParameterExpression). FYI, there are several types of expressions(BinaryExpression, ConditionalExpression, ConstantExpression etc) that is derived from base Expression class. Also, Body is of type Binary Expression. So lets take an expression and dissect it.

Analyzing an Expression Tree

ay we have a function representing delegate  Func<int, bool>. The expression is:

Expression<Func<int, bool>> expressionTree =(i => i> 5);  

The expression has subparts that has shown in the image below

image

Here in the above statement we see the lambda expression takes an integer value and check if the value is greater than 5 or not and return a boolean value. The above expreesionTree variable's two property we have used in the code below. One is parameters collection and another one is Body. Parameters collection is of length one as we have only one parameter i

//This is i before the lambda expression

ParameterExpression param = expressionTree.Parameters[0] as ParameterExpression;

//this is the body of the expression, right side of lambda operator (=>). i.e., i>5

BinaryExpression  body=expressionTree.Body as BinaryExpression;

//This is the the i in the body. I.e., i on the left side of greater than

ParameterExpression left = body.Left as ParameterExpression;

//This is the constant in the body. That is 5

ConstantExpression right = body.Right as ConstantExpression;

Console.WriteLine("Docomposed Expression: {0} => {1} {2} {3}", param.Name, left.Name, body.NodeType, right.Value);

Building an Expression Tree

We can build the same expression tree that we have seen in above (for expression i=>i<5). All we need to do to generate different expressions (BinaryExpression, ConditionalExpression,ConstantExpression etc) and combine these properly into a single expression. Finally we need to compile and invoke the expression. A shown in the code snippet below, we can use Expression static methods to generate various types of expressions. we can generate a full function from that expression with Expression.Lambda method.

 

//bulild the prarameter expression

ParameterExpression param=Expression.Parameter(typeof(int),"i");

//build the constant expression

ConstantExpression constant = Expression.Constant(5, typeof(int));

//build the binary expression

BinaryExpression numLessThanAndEqual = Expression.LessThanOrEqual(param, constant);

//build the whole expression. that is body

Expression<Func<int, bool>> func = Expression.Lambda<Func<int, bool>>(numLessThanAndEqual, new ParameterExpression[] {param });

//complile the expression

Func<int,bool> compiledFounction = func.Compile();

//invoke the expression

compiledFounction.Invoke(10);

 

References

http://msdn.microsoft.com/en-us/library/bb397951.aspx

Friday, June 19, 2009

Lambda Expression: Basic and benefits

Generally, a Lambda Expression is anonymous function that use lambda expression (=>) which is read as "goes to". The format of the lambda expression is as follows:

parameters => body

Here if number of parameters is one the parenthesis is optional. If more than one parameters are used then parameters need to inside parenthesis. Also if the number of statements in body part is one then no second bracket is needed but if number of statement is more than one then statements need to inside second bracket. In the following code snippet I have declared two delegates. One represent integer binary operation signature and another is for unary operation signature.

 

The delegate with unary integer operation signature is as follows:

delegate int DelUnary(int i);

In the above statement the delegate name is DelUnary and it taken an integer value and return an integer value.

 

The delegate with binary operation signatue is as follows which takes two integer value and return an integer value:

delegate int delBinary(int t, int x);

 

Now lets talk about unary delegate. We need two methods for incrementing and decrementing values. So we can define these two functions and assign those two functions in a variable of type DelUnary as shown below:

            DelUnary increment = x => x++;

            DelUnary decrement = x => {x--};

In the above statement we have declared an variable (increment , decrement) of type DelUnary and then we have defined the body of the methods (increment, decrement). The body start after equal sign (=). The body part (x=x++;) or (x=>x--) has two parts. The left part of lambda operator (=>) is parameter (i.e., x) and right part of the lambda expression is the method body. The body may contains multiple statements but its recommended not to be more than 2/3 lines. In case of multiple statements you need to use curly braces({}) for enclosing statements.

Now we can call the method as

            int i=0;

            Console.WriteLine(increment(i));

            Console.WriteLine(decrement(i));

 

Similarly we can declare binary functions and call them as shown below:

            delBinary multiplication = ((x, y) => x * y);

            delBinary summation = ((x, y) => x * y);

            delBinary subtraction = ((x, y) => x * y);

 

            int m = 5;

            int n = 10;

            Console.WriteLine(multiplication(m, n));

            Console.WriteLine(subtraction(m, n));

            Console.WriteLine(summation(m, n));

 

Lambda expression allows us to write small code to do more. Lets say we have a collection of names and we need to find person whose name start with "mar". So in conventional C# we write something as shown below:

 

        string[] names = { "smith", "john", "mike", "mark", "seth", "maria", "manson" };

        IList<string> foundNames= new List<string>();

        foreach (string name in names)

        {

            if (name.StartsWith("mar"))

            {

                foundNames.Add(name);

            }

        }

 

But with lambda expression we can easily shorten the above code into small and more neat form as shown below:

string[] names = { "smith", "john", "mike", "mark", "seth", "maria", "manson" };

IList<string> foundNames = names.Where(s => s.StartsWith("mar")).ToList();

Isn't that goo huh? I like this coding style very much and I have used this style in my few new projects. Believe me I'm enjoying this coding style. When I started using lambda expression for the first time it was a kind of wired stuff to me. But as I'm exploring I'm finding this really interesting and I personally believe that it will increase programmer productivity as programmer need to write lees code.

Next time I'll explain Lambda Expression Tree which is also interesting.

Wednesday, June 17, 2009

CLR and .Net Framework: Some information to share

.Net Framework 4.0 in on the way and Vance Morrison, an CLR architect has talked about the how CLR has evolved from the the very beginning to till now. With .Net Framework 2.0 CLR version 2.0 was released. But with .Net Framework 3.x the CLR version was the same, i.e., CLR version 2.0. Now with .Net Framework 4.0 CLR version 4.0 is going to be launched. So Where is CLR version 3.0? Actually this does not exists and will never exists. To keep the CLR and .Net Framework version consistent CLR is named from 2.0 to 4.0.  I have recently come to know some new information about CLR and .Net Framework that are summarized below:

We can see source code of an assembly (if it's not encrypted) with reflector. Doesn't it break intellectual property?

Reflector unveil the source code and someone raise question about intellectual property but just unveiling source code doesn't mean the everything. A successful software system is more than just source code. Successful system is composed of dev team, test team, marketing policy, support team etc

Exception Modeling in CLR need to be optimized (As  per CLR Architect Vance Morrison)

The exception modeling in .net framework need to optimized. But the problem is that this will change the way programmer works. So changing the exception modeling, exiting exception handling may not work.

String Manipulation in CLR can be optimized (As per CLR Architect Vance Morrison)

By default string in .net takes two bytes of space as this is Unicode string. But in real world most of the systems are not multilingual system and needs only ANSI characters. So this is kind of waster of resources. Also more than 25--30% of the total resources in a system is string. So reducing the string size to half we can save around 10-15% of resources. So as per Vance Morrison, he has a vision to do something to make the string types configurable so that developers can specify which string they want to use.

Interface uses may create problem from version to version

We can't add default implementation of a method in an interface. For example in a class library version 1 an interface Interface1 has two methods. But in version 2 another one method is added. The problem is that with that new version of class library the older code will break. So Microsoft is working on .net framework to provide a way to say version 2 that "hey If this new method doesn't exist then create a default method"

Why multiple inheritance is not supported in c#?

The simple question is to make the implementation easier. If a class ClassA inherited from three different base class Base1, Base 2 and Base3 and each of them has a property (i wanna say state foo) then in composite object ClassA it might be difficult to find out which foo is to be incorporated in derived class. Some programming languages like C++ has virtual concept which may solve the problem but it make the inheritance model more complex and dotnet framework did not follow the path. These problem becomes even complex with diamond problem. State(class fields) are bad in this multiple inheritance as you need to decide which state to keep in case of multiple inheritance. But multiple contracts (methods) are fine as we can call the base contract(method) from derived one with prefixing base one (say Interface1.Contract1(), Interface2.Contract1() etc). So whether to allow multiple inheritance or not was a design problem for CLR designer and they choose not to allow multiple inheritance to avoid complexity with implementation. If multiple inheritance is supported then developer had to dealt with problems like diamond problem.

Monday, March 9, 2009

Tuple in C# 4.0

C# 4.0 include a new feature called Tuple. In mathematics tuple is a ordered list of specific number of values called the components of the tuple. For example a 3-tuple name may be used as: (First-Name, Middle-Name, Last-Name).

Let's take a look in the following example:

        public Tuple<int, int> GetDivAndRemainder(int i, int j)

        {

            Tuple.Create(i/j, i%j);

        }

        public void CallMethod()

        {

            var tuple = GetDivAndRemainder(10,3);

            Console.WriteLine("{0} and {1}", tuple.item1, tuple.item2);

        }

 

In the above example the method can return a tuple which has two integer values. So using tuple we can return multiple values. So this will help lazy programmers to write less code but do more. One great use of tuple might be returning multiple values from a method.


To get more info on Tuple visit the following links:

http://en.wikipedia.org/wiki/Tuple

http://peisker.net/dotnet/tuples.htm

http://spellcoder.com/blogs/dodyg/archive/2008/10/30/16319.aspx

Monday, February 23, 2009

Destructor, Finalizer, Dispose

The three terms Destructor, Finalizar and Dispose are a bit confusing in dot net. May be you have heard of Finalizer and Dispose but not of Destructor. If your code uses resources that need to released then you can implement IDisposable interface. Then in Dispose method you can clear the resources. But the dispose method is not called automatically rather the user will have to call it explicitly. But if user forgets to call dispose method then how you'll release the resource? Here the Finalizer comes into play. If you implement Finalizer interface then the GC will call the finalize method when the GC will try to reclaim the memory occupied by your object. So Finalize your ensure that you cleaning code will run as GC will call it automatically. But then what about destructor? Actually destructor is just finalizer. In C++ destructor will be called when the object will go out of scope but in C# the desctructor will be called by GC (just like finalizer). So desctructor and finalizer is the same in a sense. In VB.NET there's no destructor but only Finalizer.

Finalizer is costly process and increase the object's generation by 1. When GC runs and try to collect the object and find the object has finalize method, then GC run the finalize method. And after that the GC will not collect the memory rather upgrade the object's generation by 1. So if the object in GEN 0 has finalize method called then the object will be not be reclaimed in this GC call rather the object's generation will be upgraded to GEN 1. So this will keep the object long time in memory. The object memory may be collected next time when the GC will run.

The best design is to include both dispose and finalize in the object which need to clear resources. But if user calls dispose method then we don't need to run the finalize method as the resources are already cleared in dispose method. In that case we can suppress the finalize method by calling GC.SuppressFinalize method. When this method will be called in dispose method the finalizer will not be called thus reclaiming the memory on one single GC run. But if user does not call dispose method then finalizer will be called by GC. For details follow the link:

http://msdn.microsoft.com/en-us/library/b1yfkh5e(vs.71).aspx

Thursday, February 19, 2009

CLR Profile

Few days ago I was looking to find if I can spy may dot net application to get what's doing CLR under the hood. Then I had found an amazing tool, CLR profiler. I think most people doesn't know about it or are not used to with it. I have found the tool amazing for identifying some issues like memory leak. There are two versions of CLR profiler: for .net version 1.1 and version 2.0.

With this tool we can easily find the following three issues:

1. Is our application allocating too much memory?

2. Which objects are staying in memory too much time?

3. If we are holding memory but not relasing properly.