Delegates

In this article we will try to understand what is delegate, how to use it.

Dictionary meaning:A person sent or authorized to represent others “or “A person designated to act for or represent another or others

History of Delegate in C#
The diagram shows the history of delegates by C# version,

delegates_ev

A delegate is a class that can hold a reference (source of information) to a method. We can say that delegate is like a pointer to a function.

Every delegate object is implicitly derived from class Delegate.

Declaration of Delegate:
A delegate can be declared using delegate keyword followed by a function signature as shown below:

Signature of a Single Cast Delegate:

 delegate  (< parameter list >)

Example:

public delegate void myDelegate(string myMessage);

Delegate class has four steps process for defining and using delegates – Declaration, Reference, Target and Invoke.

The first step is to declare the delegate with the return type and input parameters.

// Delegates declaration
public delegate int myDelegate(int a, int b);

Which is having same signature as method below.

public int Sum(int a, int b)
{
    return a + b;
}

The Second step is to create a delegate reference.

// Create delegate reference
DelegateClass.myDelegate objSum = null;

The third step is to target/point the delegate reference to an object instance.

// Target the reference to the Sum method
objSum = objMyclass.Sum;

The final step is to invoke the delegate, like as invoking a regular method.

// Invoke the delegate
Console.WriteLine("Sum of two integer is = " + objSum(10, 20));
Console.ReadLine();

Finally the Sample Code:

namespace DelegatesProperties
{
    class DelegateClass
    {
// Delegates declaration
        public delegate int myDelegate(int a, int b);

       // Methods to Target & called by delegate
 public int Sum(int a, int b)
        {
            return a + b;
        }
    }

    class Program
    {
        
        static void Main(string[] args)
        {
            DelegateClass objMyclass = new DelegateClass(); 

            // Create delegate reference
            DelegateClass.myDelegate objSum = null;

            // Target/Point the reference to the Sum method
            objSum = objMyclass.Sum;

            // Invoke the delegate
            if (objSum != null)
            {
                Console.WriteLine("Sum of two integer is = " + objSum(10, 20));
                Console.ReadLine();
            }        }
    }
}

Output: Sum of two integer is 30;

Let’s do it with Anonymous Method:

namespace DelegateAnonymous
{
    class DelegateClass
    {
        // Delegates declaration
        public delegate int myDelegate(int a, int b);
    }
    class Program
    {
        static void Main(string[] args)
        {
            DelegateClass objMyclass = new DelegateClass();

            // Create delegate reference
            DelegateClass.myDelegate objSum = null;

            // Point the reference to the Sum method
            objSum = delegate (int a, int b) // Anonymous Method
            {
                return a + b;
            };

            // Invoke the delegate
            //objSum.Invoke(20, 10);

            if (objSum != null)
            {
                Console.WriteLine("Sum of two integer is = " + objSum(10, 20));
                Console.ReadLine();
            }
        }
    }
}

Output will be the same as before, this time we have made a little bit change to point the method.Here we use an annymous method, let’s take a look how:

objSum = delegate (int a, int b) // Anonymous Method
{
   return a + b;
};

And the Sum method is no more exist in the DelegateClass

public int Sum(int a, int b)
{
   return a + b;
}

Types of delegates:

  1. Single cast delegate
  2. Multi cast delegate

Single Cast Delegate:
A single cast delegate holds the reference of only single method. This type of delegate is derive from the System.Delegate class.

Note: Our previous Example is a single cast delegate

Multi Cast Delegate:
The delegate can points to multiple methods. Class MulticastDelegate derives from Delegate and represents a delegate that can invoke more than one method at once.

Internally, MulticastDelegate is implemented as a linked list of delegates.

Add/Remove Delegates:
All delegate types declared in C# have implicit operators += and -=. The “+” operator adds a function to the delegate object and the “-” operator removes an existing function from a delegate object. 

Sample Example:

namespace MulticastDelegates
{
    class DelegateClass
    {
        // Delegates declaration
        public delegate void myDelegate(int a, int b);

        // Methods to Target & called by delegate
        public void Sum(int a, int b)
        {
            Console.WriteLine("Sum of two integer is = " + (a + b));
        }

        public void Divide(int a, int b)
        {
            Console.WriteLine("Divide of two integer is = " + (a / b));
        }

        public void Multiply(int a, int b)
        {
            Console.WriteLine("Multiply of two integer is = " + (a * b));
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            DelegateClass objMyclass = new DelegateClass();

            // Create delegate reference
            DelegateClass.myDelegate objSum = null;

            // Point the reference to the Sum method
            objSum += objMyclass.Sum;
            objSum -= objMyclass.Divide;
            objSum += objMyclass.Multiply;

            // Invoke the delegate
            if (objSum != null)
            {
                objSum(20, 5);
                Console.ReadLine();
            }
        }
    }
}

Output:
Sum of two integer is 25;
Divide of two integer is 4; not showing this time.
Multiply of two integer is 100;

Key Notes:

  1. Delegates are reference type.
  2. Delegates are type-safe.
  3. Delegates encapsulates one or more methods.
  4. We can invoke all the methods the delegate is encapsulating with a single call
  5. Delegates allow methods to be passed as parameters.
  6. Invoking a delegate is like as invoking a regular method.
  7. Delegates are used in event handling for defining callback methods.
  8. Once a delegate is created, the method it is associated will never changes because delegates are immutable in nature.
  9. Delegates provide a way to execute methods at run-time.
  10. All delegates are implicitly derived from System.MulticastDelegate, class which is inheriting from System.Delegate class.

Author:

Since March 2011, have 8+ years of professional experience on software development, currently working as Senior Software Engineer at s3 Innovate Pte Ltd.

One thought on “Delegates”

Leave a Reply