DEV Community

Jai
Jai

Posted on

Programming with Delegates

So What are Delegates in English? Delegate means a person sent or authorized to represent others, in particular, an elected representative sent to a conference. Now we keep hearing the news that delegates of the two countries met and discussed some underlying issues. Similarly, Delegates are nothing more than communication between two entities where some information can be exchanged among the entities.

According to Wiki, In object-oriented programming, delegation refers to evaluating a member (property or method) of one object (the receiver) in the context of another original object (the sender). In the c# programming world, a callback is tied to an event and when an event occurs a callback method is fired using a delegate. For example, when you click on a button an event is triggered and a corresponding callback action is executed. But how did the program understood which callback to execute? It is done via Delegates. A delegate holds the reference(delegates are also called function pointer because of the same reason) of methods and can be used to chain callback methods.

Delegate in c# is defined as:

[modifier] delegate [return_type] delegate_name;

Example:

public delegate int GoForestGo(int G, int F, int G);

modifier: It is the required modifier which defines the access of delegate and it is optional to use.
delegate: It is the keyword which is used to define the delegate.
return_type: It is the type of value returned by the methods which the delegate will be going to call. It can be void. A method must have the same return type as the delegate.
delegate_name: It is the user-defined name or identifier for the delegate. parameter_list: This contains the parameters which are required by the method when called through the delegate.

Below is an example of a simple delegate where we are creating a class and declaring a delegate which will take a number and perform the print operation. Let us declare a method LetsPrint which is printing all the numbers which are divisible by 2. We are invoking a callback for every success scenario and printing the number.

public delegate void CallBack(int i);

public class Program
{
    private static void Main(string[] args)
    {
        NewClass instance = new NewClass();
        instance.LetsPrint(CallBack);
    }

    private static void CallBack(int i)
    {
        Console.WriteLine(i);
    }
}

public class NewClass
{
    public void LetsPrint(CallBack obj)
    {
        for (int i = 0; i < 100; i++)
        {
            if (i % 2 == 0)
            {
                obj(i);
            }
        }
    }
}

Multicast Delegates

A delegate can hold the reference of one or more methods. Now in our above example, our delegate was holding only one reference of a callback method, but when a delegate holds more than one reference it is called multicast delegates. Have a look to the below code snippet:

public delegate void CallBack(int i);

public class Program
{
    private static void Main(string[] args)
    {
        NewClass instance = new NewClass();
        CallBack callBack = null;

        callBack = CallBack_Method1;
        callBack += CallBack_Method2;

        instance.LetsPrint(callBack);
    }

    private static void CallBack_Method1(int i)
    {
        Console.WriteLine("Callback1: " +i);
    }
    private static void CallBack_Method2(int i)
    {
        Console.WriteLine("Callback2: " + i);
    }
}

public class NewClass
{
    public void LetsPrint(CallBack obj)
    {
        for (int i = 0; i < 10; i++)
        {
            if (i % 2 == 0)
            {
                obj(i);
            }
        }
    }
}

In the above example, we are invoking 2 callbacks by chaining them together. Similarly, we can chain multiple callbacks to a delegate. We are invoking LetsPrint and passing chained delegates which will be executed after every successful execution.

I hope you have understood the concept of delegates and callbacks after reading the article. Please do share your valuable feedback.

Top comments (0)