When a head of state dies, the President of the United States typically does not have time to attend the funeral personally. Instead, he dispatches a delegate. Often this delegate is the Vice President, but sometimes the VP is unavailable, and the President must send someone else, such as the Secretary of State or even the First Lady. He does not want to “hardwire” his delegated authority to a single person; he might delegate this responsibility to anyone who is able to execute the correct international protocol.

The President defines in advance what responsibility will be delegated (attend the funeral), what parameters will be passed (condolences, kind words), and what value he hopes to get back (goodwill). He then assigns a particular person to that delegated responsibility at “runtime” as the course of his presidency progresses.

From the book of Programming C#
By Jesse Liberty, Brian MacDonald

In programming, the delegate is a type that holds a reference to a method with a matching parameter list and return type. We can call it a type-safe function pointer. A delegate is a reference type just as a class. I hope you remember the difference between a reference type and a value type.

If you remember that in method overloading, the return type of the method is not included in the signature of that method, however when we talk about delegates, the signature includes the return type as well, i.e. the return type of the method, to which a delegate is pointing, should be same as that of the delegate itself.

For example:
Let’s take an example of UPI Payment, where UPI is holding the reference of your bank account when any transaction occurs it will call respective methods in your bank account. So, we can say UPI is a delegate which holds a reference of your bank.

To call a non-static method by using the instance of the class and a static method by using the name of the class. We can also call a method by using a delegate. We will see how.

Defining a delegate

We define a delegate by using the following syntax:

[modifiers] delegate [type] [delegate-name]([parameter-list]);

Notice that the syntax of defining a delegate is exactly similar to that of declaring a method, there is just one extra word and that is “delegate”.

So, if we have to define a delegate for the following method:

public int Add(int x, int y)
    return x + y;

We do it in the following way:

public delegate int AddDelegate(int x, int y);

Notice that we have just added “Delegate” in the name of the delegate, you can name your delegate anything you want.

We just have to remember two things while defining a delegate:

  • The return type of the delegate should exactly be the same as that of the method.
  • The parameter list of the delegate should match exactly with the parameter list of the method. This does not mean that the parameter names have to be the same. The number of parameters and type of the parameters should be same. This is the reason we call a delegate to be type safe.

Instantiating a delegate

When we instantiate a delegate, we have to pass the name of the method to the delegate constructor as a parameter. So if we instantiate our AddDelegate, we need to pass the Add() method to the AddDelegate constructor as a parameter as follows:

AddDelegate addDelegate = new AddDelegate(classInstance.Add);

We require an instance name to pass the Add() method as a parameter to the delegate as Add() is a non-static method and non-static methods require an instance for accessing.

So, now “ad” holds the reference or the address of the method Add().

Calling the delegate

We call the delegate by passing the required parameters so that internally the method which is attached with the delegate gets executed.

We can call the delegate in the following two ways:

• ad(100, 200); //By passing the parameters.

• ad.Invoke(100, 200); //By calling a method called “Invoke”

So, the whole program will look like this:

Code for Program class:

namespace Delegaters
    class Addition
        public int Add(int x, int y)
            return x + y;

Code for Initialize class:

using System;

namespace Delegaters
    class Program
        //Define a delegate
        public delegate int AddDelegate(int x, int y);

        static void Main()
            var addition = new Addition();

            //Instantiating a delegate
            var addDelegate = new AddDelegate(addition.Add);

            //Calling the delegate
            //By passing the parameters.
            var result = addDelegate(1090, 2100);

            //By calling a method called “Invoke”.
            result =addDelegate.Invoke(190, 20);

Where to use delegates?

In programming we often faced with situations where we need to execute a particular action, but we don’t know in advance which method, or even which object, we want to call upon to execute it.

For Example: A button might not know which object or objects need to be notified. Rather than wiring the button to a particular object, you will connect the button to a delegate and then resolve that delegate to a particular method when the program executes.

Typical delegates are used in events declaration and call-back method.

Delegates Overview

  • Delegates are similar to C++ function pointers but are type safe.
  • Delegates allow methods to be passed as parameters.
  • Delegates can be used to define call-back methods.
  • Delegates can be chained together; for example, multiple methods can be called on a single event.
  • Delegates can also be used in “anonymous methods” invocation.

In simple words, delegates are object-oriented and type-safe and very secure as they ensure that the signature of the method being called is correct. Delegates make event handling simple and easy.

C# Delegate Online free quiz to test your knowledge.

Leave a Reply

Your email address will not be published. Required fields are marked *