Tuesday, June 2, 2009

Delegates & Events


This time I am trying to expound one of the most controversial and debated topics of .NET with a hope in the heart that it makes a sense to the readers. I honestly welcome any critics or suggestions needed for the improvement of this article.
What are the Delegates?
Delegates are nothing but array of addresses of the methods. The word “Array of Addresses” is used here because a delegate can contain addresses of several methods.But the delegates are type safe; as a result a delegate can contain the addresses of a similar type of methods.
Declaring a Delegate
The delegate is declared in the following way
private delegate Method Return Type myDelegate (Method Parameters);
More specifically suppose I want to declare a delegate for the method
private int myMethod1 (int x, int y);
it can be declared as follows
private delegate int myDelegate (int x, int y);
Assigning method to the delegates
The method myMethod1 can be assigned to the "myDelegate" in the following way.
myDelegate=myMethod1;
Now suppose there are following methods which have got similar signature and return types.
private int myMethod2 (int x, int y);
private int myMethod3 (int x, int y);
private int myMethod4 (int x, int y);
Then these methods can also be added in the "myDelegate" in the following way:
myDelegate+=myMethod2;
myDelegate+=myMethod3;
myDelegate+=myMethod4;
For the sake of more clarification let's assume that methods myMethod1, myMethod2, myMethod3, myMethod4 are stored at the locations 100,200,300,400 respectively then in this case our delegate "myDelegate" will be an array consisting of the elements 100,200,300,400.
This means the delegate “myDelegate” can call the all those methods when it is invoked.’A method can be removed from the delegate in the following waymyDelegate-=myMethod4;
Complier representation of Delegates
When we declare a delegate like

private delegate int myDelegate ();

The .NET generates the following class for this.

internal delegate int myDelegate(string someValue)
{
public myDelegate(object object, IntPtr method);
public virtual IAsyncResult BeginInvoke(string someValue,AsyncCallback callback, object object);
public virtual int EndInvoke(IAsyncResult result); public override int Invoke(string someValue);
}

No comments:

Post a Comment