What are C# Delegates

12 February 2021 at 10:00 by ParTech Media - Post a comment

It is always handy to split the work and assign it to multiple members so that the work can be done not just quickly but also effectively. But for this, you need the process to be flexible where you can assign tasks anytime. Similarly, in the programming world, it is always welcomed and encouraged to make the code adjustable and work according to your need at run time.

It is always recommended to use methods in a programming language. Each method should fulfill a specific purpose only so that it is easier to make enhancements to the method and make it open for changes. For example, there is a bank and it has online facilities to open accounts. It allows account openings for all age groups. But they have two different processes to open the account; they follow a process for people older than 18 years and another process for people less than 18 years. But, if we see it from a holistic point of view, it is the account opening that is being done.

So, the programmers write two separate methods with the two account opening logics. But, during the time of code compiling, the developers have little knowledge on which will be executed. There are multiple ways to handle the runtime method calling part, but one handy way is to use the delegates and call the appropriate method as required. Let's see in detail what is C# delegate, how a delegate is created, referenced, and executed.

Table of contents

  1. What are C# Delegates?
  2. Working with Delegates
  3. Conclusion

What are C# Delegates?

Delegates are a type that is used to hold the references of methods with a particular parameter list and return type. It is used to pass the method as an argument to another method. Delegates when instantiated can accept any methods that have the mentioned signature and return type.

Desired methods can be called using the instance of the delegate. Events handlers in C# are one such example for delegates. Delegates are usually compared with the pointers in the C/C++ programming language, as they are reference type variables and hold the reference for methods.

Working with delegates

In this section, let us see how to work with delegates.

Declaring a delegate

Delegate declarations are similar to the declaration of methods in C#. The additional change is the inclusion of the keyword delegate in the declaration part. The syntax for delegate declaration is -

delegate <return type> <delegate name> <parameter list>

For example,

Public delegate int MyDelegate (int number1, int number2);

Here,

  • Public is the access specifier
  • Delegate is the keyword that represents the delegates
  • Int is the return type of the delegate
  • MyDelegate is the name of the delegate
  • The variables inside the bracket are the accepted parameters by the delegate.

Instantiating and Invoking a delegate

Delegates are instantiated similar to the object created with the new keyword. The method to be called is being passed as the parameter to the delegate. And while calling the delegate, the input parameters that are required for the executing method are being passed.

The syntax for instantiating a delegate

<delegate name> <instance name> = new <delegate name> <calling method name>

For invoking delegates, users have two ways -

Syntax - <delegate name>(input parameters); or <delegate name>.Invoke(input parameters);

Example,

  class TestClass

  {

​    public delegate int MyDelegate(int firstNumber, int secondNumber);

 

​    public static int AddNumbers(int a, int b)

​    {

​      return (a + b);

​    }

 

​    public static int SubNumbers(int a, int b)

​    {

​      return (a + b);

​    }

 

​    static void Main(string[] args)

​    {

​      MyDelegate delegateOne = new MyDelegate(TestClass.AddNumbers);

 

​      var result = delegateOne(1, 2);

 

​    	//The above line can also be invoked in the below fashion.

​    	result = delegateOne.Invoke(1,2);

​    }

  }


The above code calls the method AddNumbers using the delegateOne and the values 1 and 2 are being passed as input. It retrieves the sum of both the numbers as output.

Multicast delegate

The delegate can hold a list of methods for execution rather than a single method, this feature of a delegate is known as Multicast.

To add methods to delegates, users can make use of += overloaded operator which will add the method to the delegate. Similarly, to remove the method from a delegate, users can make use of the -= overloaded operator

class TestClass

  {

​    public delegate int MyDelegate(int firstNumber, int secondNumber);

 

​    public static int AddNumbers(int a, int b)

​    {

​      return (a + b);

​    }

 

​    public static int SubNumbers(int a, int b)

​    {

​      return (a + b);

​    }

 

​    static void Main(string[] args)

​    {

​      MyDelegate delegateOne = new MyDelegate(TestClass.AddNumbers);

​     

​    	delegateOne += new MyDelegate(TestClass.SubNumbers);

​       

var result = delegateOne(10, 2);

 

delegateOne -= new MyDelegate(TestClass.AddNumbers);

 

result = delegateOne(10, 2);

​    }

  }

In the above example, the delegate is first assigned with the method - AddNumbers, then it is added with another method SubNumbers. During the first calling part of the delegate, both AddNumbers and SubNumbers methods will be executed.

Later, the AddNumbers method has been removed from the delegate, which makes the delegate call only the SubNumbers method during the second delegate call.

Delegates for generic return type and parameters

Similar to methods of specific data return type and input parameter, delegates can be used to invoke generic type. The only difference is, the expected return type has to be specified during the initialization of the delegate object.

  class TestClass

  {

​    public delegate T MyDelegate<T>(T firstParameter, T secondParameter);

 

​    public static int AddNumbers(int a, int b)

​    {

​      return (a + b);

​    }

 

​    public static string ConcatStrings(string a, string b)

​    {

​      return (a + b);

​    }

 

​    static void Main(string[] args)

​    {

​      MyDelegate<int> delegateOne = new MyDelegate<int>(AddNumbers);

 

​      var result = delegateOne(10, 2);

 

​      MyDelegate<string> delegateTwo = new MyDelegate<string>(ConcatStrings);

 

​      var resultString = delegateTwo("One", "Two");

​    }

  }


Conclusion

To summarize, delegates are reference type data types that define the signature of the methods which in turn can be called using it. They can be called using multiple ways and can hold multiple methods. A multicast delegate provides the last calling method value as the final value.

Latest