Delegates in C# | Multicast Delegate with Examples

In this post, we`ll discuss about C# delegates and their various types.

Delegates In C#
Delegates In C#

A delegate is a (reference) type that holds references to methods with a particular parameter list and return type. You can associate a delegate’s instance with any method that has a compatible signature and return type. You can call the method through the delegate instance.

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.

delegate in c#
C#Delegates

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>)

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

The following are the delegate types in C#

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

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

 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: Multicast delegates

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.

C# Anonymous method using delegate keyword

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 function pointer. The method that the delegate will use must have the same parameters and return types as the delegate.
In C#, A multicast delegate is used to point to multiple methods having similar signatures, and a plus “+” and “” operator is used to add or remove the delegates from the invocation list. Delegates generally help to implement callback methods and events.

FAQs

Q: Why do we need multicast delegates in C#?

Ans: Multicast delegates allow the user to point more than one method in a single call having the same signature and return type.
The multicast delegate contains a list of the assigned delegates. When the multicast delegate is invoked, it calls the delegates in the invocation list in order. Only delegates of the same type can be combined in the invocation list.
A multicast delegate can be used to implement the observer design pattern.

Q: How delegates are used in C#?

Ans: A delegate is a type that holds references to methods with a particular parameter list and return type.

Q: Why should I use delegates instead of directly invoking the method in C#?

·        You may sometimes need to pass a method as a parameter to another method, so in that case, you’ll need delegates.
 
·        Delegates are commonly used for event handling, allowing a function to be invoked by a module that has no knowledge of the function’s implementation.
Delegates come in handy when components need to notify other components that they’ve subscribed. It can be used to implement the observer pattern, often known as the publish/subscribe pattern.

Q: many types of delegates are there in C#?

Ans: There are three different types of delegates in C#. Single Delegate, Multicast Delegate, and Generic Delegate

Q: Can delegates be private in C#?

Ans: Yes, delegates can be declared as private, public, or internal just like classes.

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

References MSDN: C# Delegates

Recommended Articles

Leave a Comment