What is the exact use of Delegate in C#?


This is the one of the frequently asked question in interview.Generally in interview, we will tell that “Delegate is the function pointer”. But this is not the exact answer of Delegate.

In the simple word “Delegate is the representative who helps us to make data communication between two parties”.

So in C# also Delegate is the process of doing data communication between two parties and main use of delegate is the callback.

Now let see the example, how delegate is making callback communication between two parties.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DelegateTest
{
class Program
{
static void Main(string[] args)
{
MyClass obj = new MyClass();
obj.LongRunningMethod(CallBack);

}
static void CallBack(int i)
{
Console.WriteLine(i);
}
}
class MyClass
{
public delegate void CallBack(int i);
public void LongRunningMethod(CallBack obj)
{
for (int i = 0; i < 10000; i++)
{
obj(i);
}
}
}
}

Delegate

Now in the above program, There are two class I.e. Program and MyClass . In myclass we have created one LongRunningMethod which is used for looping the number and we have created one delegate i.e Callback

In Program class, there is static Callback Method and Main Method. Now my requirement is there to whenever loop will execute then callback should happen and data should pass to Program class. Then I can use representative i.e. Delegate which will do my callback task.

For that I have created static Callback Method in Program Class and Callback delegate in MyClass and I am passing the object of Callback in LongRunningMethod as in above example.
In program class I am creating the object of MyClass then I am accessing the longRunningMethod and I am passing Callback method as Parameter.

So in this ways we are making the data communication between one class to other class using delegate.

Summary:
In the above example we saw that “Delegate in the representative which helps us to make data communication between two parties”.

Advertisement

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.