Delegate in C#

Delegate in C#

I am not going to write formal definition here because you will find lots of definition of delegate by googling. Most of the time, new developer faces problem with delegate. They think actually what it is and why they use it instead of method.

In simple word: What is Delegate?
Delegate is a method reference in C# or Delegate is a function pointer in other language like C/C++.

Or you can think
Delegate can be seen as a placeholder for a/some method(s).

Now question is why we need this, means why we need to reference a method?
The answer boils down to giving you maximum flexibility to implement any functionality you want at runtime.

By defining a delegate, you are saying to the user of your class “Please feel free to put any method that match this signature here and it will be called each time my delegate is called”.

Not clear? Ok let’s go with an example

Simple Example
Suppose you have a win forms application like following

Delegate in C#, Example of Delegate
Fig: 1. (Showing how we can use delegate in C#)

>Now you are asked to perform Addition or Subtraction operation by pressing “Calculate” button. Calculate button will perform operation based on user click “+” or “-” button on runtime.
>Now the point is Calculate button doesn’t know what operation it will perform; addition or subtraction. The interesting point is user will define it run time by pressing “+” or “-” button at runtime.
>If user press “+” button then Calculate will perform addition operation and if “-” button then it will perform subtraction operation.
You may ask what difficulties here are? It is simple. But if you are asked to do it without any if-else programming then what you will do? You are thinking right…..:)

Now Delegate is ready to help you to solve this problem…. How? Let’s see

Suppose you have a delegate called delegateCalculate and two methods Addition and Subtraction. Now under your calculate button [from fig 1] you just call delegateCalculate(X1,X2); Then this call can perform Addition or subtraction. If user Press “+” button then I will reference delegateCalculate to Addition method and if user press “-” button then I will reference delegateCalculate to Subtraction method.

So what are we found?
We just calling delegate and delegate calling addition or subtraction method at run time based on user input.

Still Confusing?
Let’s consider about variable “a” typed int.
What we can do with it? We can assign value and then get value when necessary.
Consider example

//assigning
Int x =10;
x = 10+2;

//getting value
Console.WriteLine(x.ToString());

Now consider about delegate.
In variable x we can assign value. Like X =10;
In delegate we can assign method like

del = new DelegateX(“your method name”);

So in variable we can assign value, in delegate we can assign method.

I think it is clear now.

If not, let’s try with sample code.

Before going details
How to declare delegate

public delegate int delegateCalcualte(int x1,int x2);

We can assign any method which has return type int and two input parameter typed int.

How to instantiate

delegateCalcualte d;
d = new delegateCalcualte(Sub); // Here Sub is a method name which takes two int and returns result as int
or
d = new delegateCalcualte(Add); // Here Add is a method name which takes two int and returns result as int

Lets see our complete example
1. Declare delegate which will accept method with two input parameter and return integer value.

public delegate int delegateCalcualte(int x1,int x2);

2. Develop two methods Add and Sub for performing Addition and subtraction.

private int Add(int x, int y)
        {
            return x+y;
        }
        private int Sub(int x, int y)
        {
            return x-y;
        }

3. Then assign method to delegate on run time; under button click event

private void btnSubtruct_Click(object sender, EventArgs e)
        {
            d = new delegateCalcualte(Sub); // Here Sub is method name
        }
private void btnAdd_Click(object sender, EventArgs e)
        {
            d = new delegateCalcualte(Add); // Here Add is method name
        }

4. Then call delegate from calculate button.

//we can call by d(5,10);
textBox3.Text = d(int.Parse(textBox1.Text), int.Parse(textBox2.Text)).ToString();

Download Project

  • Fauzul

    Nice one.

  • http://www.facebook.com/md.shakhawat.hossain Riyad Optimistic

    very nice and go ahead