What is a delegate in C#? Multicast Delegate with Examples

delegate in c#

C# Delegates with Examples

In C#, a  Delegate  is a reference type that is available in system namespace.

A delegate is a wrapper of a function, or simply we can say that it is a Typesafe function pointer which can hold the reference of one or more methods of the same signature and return type.

Syntax to define a delegate in C#

In C#, The declaration of a delegate is very similar to a method signature. It can also have parameters and the return type as a normal method.

Following is the syntax to declare a delegate.

<AccessModifier> delegate <ReturnType> <DelegateName>(<Parameters>)

Example of delegate in C#

Following is the example of the single cast delegate in C#.

using System;
namespace DelegateExample
{
    // Defining a delegate to refer the methods having same signature.
    public delegate void MyDelegate(string message);

    class Program
    {
        // Defining a method
        public static void Print(string message)
        {
            Console.WriteLine($"{message}");
        }
        static void Main(string[] args)
        {
            // Instantiating delegate and passing the method name
            // as a parameter which have the same signature

            MyDelegate myDelegate = new MyDelegate(Print);

            myDelegate.Invoke("Hello Shekh");

            // Or
           // myDelegate("Hello Shekh");

            Console.ReadLine();

        }

        // Output: Hello Shekh
    }
}

Example: Callback notification using delegate

using System;
using System.Threading;
namespace DelegateExample
{
    public delegate void MyDelegate(int num);

    class DelegateCallBack
    {
        public static void LongRunningMethod(MyDelegate myDelegate)
        {
            for (int num = 1; num <= 5; num++)
            {
                Thread.Sleep(TimeSpan.FromSeconds(2));

                myDelegate(num);
            }
        }
    }
    class program
    {
        public static void Main()
        {

            DelegateCallBack.LongRunningMethod(Print);

            Console.ReadLine();

        }
        public static void Print(int number)
        {

            Console.WriteLine($" num : {number}");

        }
    }
}

Following is the result after executing the above program.

callback notification using delegate

As per MSDN:

The  Delegate  is an abstract class and it is the base class for all the delegate types.

Even though it is an abstract class only the compilers can derive explicitly from the Delegate class or from the MulticastDelegate   class, not the user.
It is not allowed to derive a new type from a delegate type.

The Delegate class is not considered as a delegate type. However, it is used to derive delegate types implicitly by the compiler.

Types Of Delegate in C#

Following are the types of delegate

    1. Single cast Delegates
    2. Multicast Delegates
    3. Generic Delegates
      • Func
      • Action
      • Predicate

Single cast delegate

 Single cast delegate  : A delegate that only holds the reference of a single method is called a single cast delegate. It is used to invoke a single method at a time.

Multicast delegate

 Multicast delegate  : In C#, a delegate that holds the references of multiple methods is known as a multicast delegate. A multicast delegate can internally hold more than one method in its invocation list which gets executed in sequence once it gets invoked.

To add multiple methods we can use  Delegate.Combine  method or  “+”  operator and to remove the reference from the invocation list  “-“  operator is used.

If we want to invoke multiple methods by using multicast delegate then all the method’s signature should be the same and return type must be  void .

Example of Multicast delegate

Example of multicast delegate using  Delegate.Combine  method.

using System;
namespace MulticastDelegate
{
    class Program
    {
        // Declaring a delegate
        public delegate void MyDelegate();

        static void Main(string[] args)
        {
         // Declares the single delegate that points to MethodA
         MyDelegate delegateA = new MyDelegate(MethodA);

        // Declares the single delegate that points to MethodB
        MyDelegate delegateB = new MyDelegate(MethodB);

        // multicast delegate combining both delegates A and B
        MyDelegate multicastDeligate = (MyDelegate)Delegate.Combine(delegateA, delegateB);
           
        // Invokes the multicast delegate
        multicastDeligate.Invoke();

        }

        static void MethodA()
        {
            Console.WriteLine("Executing method A.");
        }

        static void MethodB()
        {
            Console.WriteLine("Executing method B.");
        }

    }
}

multicast delegate output

Example of multicast delegate using “+” and “-” operator.

using System;
namespace MulticastDelegate
{
    class Program
    {
        /// Declaring a delegate
        public delegate void MyDelegate();

        static void Main(string[] args)
        {
            // Add MethodA
            MyDelegate multicastDelegate = Program.MethodA;
            
            // To MethodB
            multicastDelegate += Program.MethodB;

            // To remove MethodA from the invocation list
            // multicastDelegate -= Program.MethodA;

            // Get the list of all delegates added to Multicast Delegate.
            Delegate[] delegateList = multicastDelegate.GetInvocationList();
            Console.WriteLine($"MulticastDelegate contains {delegateList.Length} delegate(s).");
            
            // Invokes the multicast delegate
            multicastDelegate.Invoke();

        }

        static void MethodA()
        {
            Console.WriteLine("Executed method A.");
        }

        static void MethodB()
        {
            Console.WriteLine("Executed method B.");
        }

    }
}

multicast example

In the above example, a multicast delegate is used to hold a reference to the multiple methods.

Conclusion

    • In C#, a  delegate  is a wrapper of a function, or simply we can say that it is a Typesafe function pointer which can hold the reference of one or more methods of the same signature and return type.
    • Delegate support asynchronous callback as we can achieve executions of multiple methods at the same time. Asynchronous: – Parallel execution
    • By using a delegate, we can provide an alias name to a function.
    • Delegate is a wrapper of a function.
    • Delegate is also used to create an event handler for the controls created at runtime.
    • Delegate is used in lambda expression (kind of anonymous method).
    • Delegate is a type-safe function pointer that points to a function having a similar signature it doesn’t matter from which class it belongs to.

I hope you enjoyed this post and found it useful. Thanks for visiting.

Leave a Reply

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

4 + five =