We have often heard about delegate but, what is it? why do we need it? how to use it? Let’s try finding answers to these questions.

What is delegate?

In simple language, It is called pointer to a function. Delegates are used to pass methods as arguments to other methods.

It is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.

Event Handlers are nothing more than methods that are invoked through delegates. You can create a custom method, and a class such as a windows control can call your method when a certain event occurs.

Why we need delegate?

How to use it?

So far I have mentioned pretty much what you all have seen everywhere. Let's try to understand with an example:

Understanding about Delegates in C#

In the above example, I have taken a LongRunningClass which has LongRunningFunction performing some long running task. Now another class member function is requesting LongRunningFunction to start the action and pass the information. To achieve this first we shall define a delegate in the LongRunningClass, and requesting to pass the information from another class by passing method as a parameter.

Types Of Delegate

Single Delegate

It is used to invoke single methods.

Understanding about Delegates in C#

Multicast Delegate

It is used to invoke multiple methods.

Points to note:

Understanding about Delegates in C#

Another approach to create Multicast Delegate

Understanding about Delegates in C#

Generic Delegate

It was introduced in .Net 3.5 so we don't need to define the delegate instance in order to invoke a methods

Func Delegate

Action Delegate

Predicate Delegate