C# Delegates

Delegates In C#
C# delegate

C# Delegate: A delegate is a 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.

There are three types of delegates in C#: 

  1. Single cast Delegates
  2. Multicast Delegates
  3. Generic Delegates ( Func, Action, and Predicate delegate)
    • A single-cast delegate holds a reference to a single method.
    • A multi-cast delegate holds a reference to multiple methods.
    • A generic delegate can hold a reference to a method with any signature.

Declaring Delegates

A delegate declaration can be seen in the following example:

public delegate int PerformAddition(int x, int y);

The preceding delegate can be used to reference any method that takes two int parameters and returns an int type variable.

The following are important points about delegates:

  • Delegates are mostly used in implementing call-back methods and events.
  • Delegates are the type-safe pointer of any method.
  • Delegates in C# can also be used to call anonymous methods.
  • Similarly to classes and interfaces in C#, delegates can be declared outside the class or nested within it. They can be marked as public, private, 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.

As seen in the example below, a delegate can be declared by using the delegate keyword followed by the function signature.

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

        }
    }
}

You will get the following 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 a delegate type. However, it is used to derive delegate types implicitly by the compiler.

delegate in c#

Singlecast delegate

A delegate that points to a single method at a time is called a single cast delegate. Singlecast delegates are derived from System.Delegate class.

Multicast Delegate

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. They are derived from System.MulticastDelegate class.

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 a multicast delegate then all the method’s signatures should be the same and the return type must be void.

Example: Multicast delegates

The following program demonstrates the multicasting of a 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.

C# Anonymous method using the 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 to 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 are delegates 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#?

1. You may sometimes need to pass a method as a parameter to another method, so in that case, you’ll need delegates.
 
2. 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: How 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.

I hope you like this article “C# Delegates“, if you have any questions, please ask your questions in the comment section below.

References MSDN: C# Delegates, Delegates, geeksforgeeks- C#|Delegates

Recommended Articles

c20e93cf99b4a0eb1e4a099de6c2c300?s=250&r=g
5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments