Delegate in asp dotnet csharp, with simple example

In csharp, delegates allow programmer to create a variable that ‘points’ to a method.

We know that variables STORES VALUES, similar way deligates STORES POINTER TO METOD.

So we can dynamically or at various time SET DELIGATE in a way that our CALL actually invokes different method.

First step when using a delegate is to define its signature.

So when we use(or point) a delegate variable, we can point only to a method that matches its specific signature.

//declare deligate signature
public delegate int myCustomDeligate(int v1, int v2);

protected void Page_Load(object sender, EventArgs e)
//deligate variable created
myCustomDeligate objPointerToMethod;

objPointerToMethod = AddNumber;
Response.Write(“At time 1 result is=” + objPointerToMethod(3,5) + “<br/>”);

objPointerToMethod = AddNumberV2;    //this is interesting our variable now pointing to second method
Response.Write(“At time 2 result is=” +objPointerToMethod(3, 5) + “<br/>”);


//one method
public int AddNumber(int a1, int a2)
return a1 + a2;

//second method with same signature,but some other logic here
public int AddNumberV2(int b1, int b2)
return b1 + b2 + 10;    //here adding numbers, and adding 10 also to it


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s