Delegates in C# | Multicast Delegate with Examples

delegate in c#

In C#, delegates are reference types available in the system namespace.
A delegate is a type-safe function pointer that can contain one or more references to methods with the same signature and return type as the delegate. Delegates are used to pass methods as parameters to other methods. Event handlers are nothing more than methods called through delegates.
The delegate in C # is very similar to the function pointer in C and C ++, but unlike the function pointer in C, the delegate is object-oriented, type-safe, and secure.

Delegates in C# – Overview

    • The Delegates in C# are very similar to C++ function pointers, but delegates are completely object-oriented and secure. Unlike C ++ pointers to member functions, delegates encapsulate both instances of objects and methods.
    • Delegates in C# help to implement callback methods and events.
    • In C#, a  delegate  is a wrapper of a function.
    • The delegate is also used to create event handlers for controls created at runtime.
    • 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.
    • The delegate in C# can also be used to call anonymous methods.
    • Like classes and interfaces in C#, we can declare delegates outside the class or nested within the class. We can mark them as private, public, or internal.

The syntax for defining delegates 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.

The following is the syntax for declaring delegates in C#.

<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

The following declaration shows how to use a delegate to declare a callback notification.

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}");

        }
    }
}

The following is the result after running 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#

The following are the delegate types in C#

    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 delegates in C#

The following code listing illustrates a multicast delegate in C#

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.

Anonymous methods with delegates in C#

We can use the delegate to invoke the anonymous method.

An anonymous method is a method without a name and return type.
It can be created using the delegate keyword and optional parameters and can be assigned to a variable of the delegate type.

The following is an example of the anonymous method.

using System;
namespace AnonymousMethodDemo
{
    class Program
    {
        // Declaring a delegate
        public delegate int MyDelegate(int num1, int num2);
 
        static void Main(string[] args)
        {
            // Instantiating the delegate using an anonymous method
 
         MyDelegate myDelegate = delegate (int num1, int num2)
         {
            return num1 + num2;
         };
 
            Console.WriteLine(myDelegate(10,20));
 
        }
    }
    // Output: 30
}

Conclusion

A delegate is a type-safe pointer to a function. The method that the delegate will use must have the same parameters and return types as the delegate.
A multicast delegate in C# is used to point to multiple methods having similar signatures, and a plus “+” and “-” operator is used to multicast. Delegates in C# help to implement callback methods and events.

Recommended Articles

    1. Generic Delegates in C# With Examples
    2. IEnumerable Interface in C# with examples
    3. Constructors in C# with Examples
    4. Properties In C# with examples
    5. 10 Difference between interface and abstract class In C#
    6. Value Type and Reference Type in C#
    7. Multithreading in C#
    8. C# Dictionary with Examples

Hope you like this article, if you have any questions, please ask your questions in the comment section below.
Thank you for visiting. 🙂

Leave a Reply