Wednesday, June 13, 2012

Anonymous Methods in .Net 2.0


As the name suggests Anonymous methods are the ones which do not have a specific name, but they do have a body, the body is in line with the method.

Anonymous methods can be seen as version 2.0 of Delegate, earlier in .Net 1.1, delegates were initialized by mapping them to explicit method names which are already defined, Anonymous methods helps us to define the methods while initializing the delegates.

Let us understand Anonymous methods with an example.

First let us declare a Delegate

delegate int AddNumberDelegate(int Number1, int Number2);

Delegates in .Net 1.1
In .Net 1.1 to initialize this delegate, we need to declare a function which will match the signature of the delegate, and later assign the function while initializing the delegate as follows.

private int AddNumber(int Number1, int Number2)
{
    return Number1 + Number2;
}
//
// Delegates in .Net 1.1
// Delegate Initialization
AddNumberDelegate Delegate_v1 = new AddNumberDelegate(AddNumber);
// Delegate Call
Response.Write(".Net 1.1 Delegate: " + Delegate_v1(1, 2));


Delegates in .Net 2.0 (Anonymous Methods)
// Delegates in .Net 2.0
AddNumberDelegate Delegate_v2 = delegate(int Number1, int Number2)
                                {
                                    return Number1 + Number2;
                                };
// Delegate Call
Response.Write(".Net 2.0 Delegate: " + Delegate_v2(1, 2));

Note that in .Net 2.0 (Anonymous Methods), we are not calling the per-defined method AddNumber (), instead we are defining the method body dynamically.

Both these versions produce the same output
.Net 1.1 Delegate: 3
.Net 2.0 Delegate: 3


Search Flipkart Products:
Flipkart.com

No comments: