Delegate Uses In C#

Introduction

This article explains a very beautiful feature of C# called delegates. The use of delegates can be very confusing for developers, like where and when to use them in actual projects.

What are delegates in C#?

The definition says a delegate is a reference type variable that holds a reference to a method/function with a specific parameter list and return type. A delegate is nothing but a type that is declared by the delegate keyword and acts as a type-safe function pointer.

Declaring a delegate in C#

public delegate void myTestDel(string Name);

When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type.

The Method getname() has the same signature and return type as the delegate.

public static void GetName(string name)
{
    Console.WriteLine("My Name: " + name);
}
myTestDel del = new myTestDel(getName);

You can invoke the method through the delegate instance or using the invoke method.

del("By Delagete call - Abhishek Singh");

 

del.Invoke("Using Invoke - Abhishek Singh ");

Delegates are type-safe function pointers. In other words a delegate is an instance of a static method or instance from a class or struct that matches the delegate type that can be assigned to the delegate. If the method signature is changed, then the same code

will start giving a compiler error due to type safety.

You can see in the following screen that the signature was changed from a string to an int code, and that has started giving a compiler error.

Delegates in C-Sharp

Delegates are very powerful since they provide a more flexible and dynamic way to call a method. In the example below the complier is unaware of the information of which the method will be called by del. The information will be given at runtime by the delegates instance constructor that is very flexible to use.

myTestDel del = new myTestDel(getName);
del("By Delegate call - Abhishek Singh");

Example

namespace Delegates
{
    public delegate void myTestDel(string Name);
    class Program
    {
        static void Main(string[] args)
        {
            // Normal Method Call
            getName("By Normal Method call - Abhishek Singh ");
            // Method Call using delegates
            myTestDel del = new myTestDel(getName);
            del("By Delegate call - Abhishek Singh");
            del.Invoke(" Using Invoke - Abhishek Singh ");
            del = new myTestDel(getLocation);
            del("Mumbai");
            Console.ReadLine();
        }

        public static void getName(string name)
        {
            Console.WriteLine("My Name: " + name);
        }

        public static void getLocation(string location)
        {
            Console.WriteLine("My Loc: " + location);
        }
    }
}

Note

  • Delegates allow methods to be passed as parameters.
  • Delegates are type-safe function pointers.
  • Delegate instances attach or detach a method at run time, making it more dynamic and flexible to use.
  • Delegates can invoke more than one method using the Multicast feature.
  • Delegates are of reference types.

Multicast Delegate in C#

Delegates can be used to assign multiple objects to one delegate instance, meaning simply execute multiple methods in sequence, meaning the delegate points to more than one function. A Multicast delegate holds delegates of the same type in the list that, when called, get invoked in sequence.

myTestDel delmultiCast = new myTestDel(getName);  
delmultiCast += getLocation;    
delmultiCast("Abhi");  

A Delegate instance can be pointed to by multiple methods using the += sign, as stated above. Basically, it adds multiple methods to one delegate instance in the invocation list.

Example

namespace Delegates
{
    public delegate void myTestDel(string Name);
    public delegate void TestMutliCast();
    public delegate int TestMutliCastint();
    class Program
    {
        static void Main(string[] args)
        {
            // Normal Method Call
            getName("By Normal Method call - Abhishek Singh ");
            // Method Call using delegates
            myTestDel del = new myTestDel(getName);
            del("By Delagete call-Abhishek singh");
            del.Invoke(" Using Invoke - Abhishek Singh ");
            del = new myTestDel(getLocation);
            del("Mumbai");
            // Mutlticast implementation with void return type
            TestMutliCast delmultiCast = new TestMutliCast(Method1);
            delmultiCast += Method2;
            delmultiCast();
            // Mutlticast implementation with void return type
            myTestDel testMulti = new myTestDel(getName);
            testMulti += getLocation;
            testMulti("Abhi");
            // Mutlticast implementation with int return type
            TestMutliCastint intMulti = new TestMutliCastint(Method3);
            intMulti += Method4;
            int i = intMulti();
            Console.WriteLine("Return Value is " + i);
            Console.ReadLine();
        }
        public static void Method1()
        {
            Console.WriteLine("Delegate 1st method called!!!!");
        }
        public static void Method2()
        {
            Console.WriteLine("Delegate 2nd method called!!!!");
        }
        public static int Method3()
        {
            Console.WriteLine("Delegate 3rd method called!!!!");
            return 3;
        }
        public static int Method4()
        {
            Console.WriteLine("Delegate 4th method called!!!!");
            return 4;
        }
        public static void getName(string name)
        {
            Console.WriteLine("My Name: " + name);
        }
        public static void getLocation(string location)
        {
            Console.WriteLine("My Loc: " + location);
        }
    }
}

Explanation

By the preceding example, I am trying to explain the implementation of Multicast delegates. You can see above that I defined three delegates with different signatures and return types. When you are using a multi-cast delegate with methods that have a void return type, the invocation of the delegate would execute the methods added in the sequence. When the return type is not void as above, in my case, it is int. Methods with Int return types are added to the delegate instance and will be executed as per the addition sequence, but the variable that is holding the return type value will have the value return from the method that is executed at the end.

In the above example, the int variable will have a value returned from the method.

Generally, a Multicast delegate is used in the observer pattern for publication and subscriber model programming.

Where to use Delegate in C#?

A Delegate can be used in various ways depending on the requirements of the project. The following are the lists of areas where a delegate can be used to provide better output and enhance the performance of the application.

  1. Method Invocation (using delegate instance).
  2. Event Handling using a delegate.
  3. Callback and asynchronous implementation.
  4. Multiple method calls using Multicast delegate.

Conclusion

A normal delegate or a Multicast delegate is a very powerful feature in C#, and it can be used by developers in various scenarios for more flexibility and a better way to improve the performance of the application.


Similar Articles