Table of contents
1.
Introduction
2.
Syntax with explanation
2.1.
Declaration of delegates
2.2.
Instantiation and Invocation of delegates
3.
Multicasting of Delegates
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

Delegates in C#

Author Ankit Kumar
4 upvotes

Introduction

Function pointers can be used to simplify code by allowing you to choose a function to execute depending on run-time information. Delegates do the same thing in C#. 

A delegate is a type that represents methods with a specific argument list and return type. We can connect a delegate's instance with any method that has a suitable signature and return type when we instantiate it. The method is invoked via the delegate instance. 

Delegates are used to pass methods to other methods as arguments. Event handlers are just methods that are invoked via delegates. We write a custom method that a class, such as a Windows control, may call when an event happens. A delegate declaration and instantiation and invocation of delegates is shown in the upcoming section with the explanations.

Syntax with explanation

Declaration of delegates

First of all, let’s take a look at the syntax:

[modifier] delegate [return_type] [delegate_name] ([parameter_list]);

Now, we’ll see what each part of syntax means:

  • modifier: This is a mandatory modifier that defines the delegate's access; however, it is optional to utilise. 
  • Delegate: It is the keyword delegate that is used to define the delegate. 
  • Return type: This specifies the type of value returned by the methods called by the delegate. It's possible that it's void. A method's return type must be the same as the delegate's. 
  • delegate_name: This is the delegate's user-defined name or identification. 
  • parameter_list: This is a list of the parameters that the method requires when called through the delegate.

Now, it’s time to understand this with an example:

public delegate int CodingNinjas(int C, int N); 

“public” is modifier

“int” is the return type

“CodingNinjas” is the delegate type

"(int C, int N)" are the parameters

The delegate can be allocated any method from any available class or struct that fits the delegate type. A static method or an instance method can be used. Because of this flexibility, we may alter method calls programmatically or add new code to existing classes.

Now, it’s time to see instantiation and invocation of delegates.

Instantiation and Invocation of delegates

Firstly, let’s take a look at the syntax:

[delegate_name]  [instance_name] = new [delegate_name](calling_method_name);

Firstly we declare the delegate. Then in the next step, the new keyword is used to construct a delegate object. A method call made to a delegate is sent to that method by the delegate after it is created. The caller's parameters are sent to the delegate, which then passes them to the method, which returns the method's return value, if any, to the caller. Invoking the delegate is the term for this.

Now, it’s time to understand the concept with an example:

CodingNinjas CN = new CodingNinjas (Ninja);

“CodingNinjas” is the delegate name

“CN” is instance_name

“Ninjas” is calling method

Delegates are great for establishing callback methods since they may refer to a method as a parameter. You may create a method in your application that compares two objects. A delegate for a sort algorithm can utilise that technique. The sort function may be broader because the comparison code is independent of the library.

Now, it’s time to understand with the help of a code.

Mulnum and divnum are the two delegates in the following programme. Because both of the methods (mulnum and divnum) are instance methods, we create the object obj of the class Ninjas. As a result, they require an object to call. There is no need to build the class object if the methods are static.

// C# program to show the use of Delegates
using System;
namespace CodingNinjas {
// declare class "Ninjas"
class Ninjas{
// Declaring the delegates, The return type and parameter type must be same 
// as the parameter type and return type of the two methods
// "mulnum" and "divnum" are two delegate names
public delegate void mulnum(int c, int n);
public delegate void divnum(int c, int n);
// method "multiply"
public void multiply(int c, int n)
{
Console.WriteLine("(75 * 25) = {0}", c*n);
} 
// method "division"
public void division(int c, int n)
{
Console.WriteLine("(75 / 25) = {0}", c/n);
} 
// Main Method
public static void Main(String []args)
{
// creating object "obj" of class "Ninjas"
Ninjas obj = new Ninjas(); 
// creating object of delegate, name as "delobj1"
// for method "multiply" and "delobj2" for method "division" &
// pass the parameter as the two methods by class object "obj"
// instantiating the delegates
mulnum delobj1 = new mulnum(obj.multiply);
divnum delobj2 = new divnum(obj.division);
// pass values to methods by delegate object
delobj1(75, 25);
delobj2(75, 25);
// These can be written as using
// "Invoke" method
// delobj1.Invoke(75, 25);
// delobj2.Invoke(75, 25);
}
}
}

Output:

(75 * 25) = 1875

(75 / 25) = 3

Now, we move to multicasting of delegates

Multicasting of Delegates

Multiple methods can be pointed to by the delegate. A multicast delegate is a delegate that points to many methods. Multiple objects can be assigned to a single delegate instance by using the + or += operator, which is a useful feature of multicasting delegate objects. Similarly, to remove a component delegate from a multicast delegate, use the -  or -= operator. 

The allocated delegates are listed in the multicast delegate. When the multicast delegate is invoked, it calls the delegates in the list in the order they appear in the list. The only delegates that can be merged are those of the same kind.

One thing to keep in mind is that delegate multicasting must have a Void return type, or else a runtime exception will occur. In addition, delegate multicasting will only return the value from the last method added to the multicast. The other ways, on the other hand, will be successful.

Now it’s time to learn with code:

In this code area and perimeter are two methods of the class square. We create objects of the class. Delegates are declared then both methods are called simultaneously. With this, multicasting is demonstrated.

// C# program to show the Multicasting of Delegates
using System;
class square {
// declaring delegate
public delegate void sqDelegate(double side); 
// "area" method
public void area(double side)
{
Console.WriteLine("Area is: {0}", (side * side));
}
// "perimeter" method
public void perimeter(double side)
{
Console.WriteLine("Perimeter is: {0} ", 4 * side);
} 
// Main Method
public static void Main(String []args)
{
// creating object of class "square", named as "sq"
square sq = new square(); 
// two lines are normal calling of those two methods
// sq.area(6.25);
// sq.perimeter(6.25); 
// creating delegate object, name as "sqdele" and pass the method as parameter           
// class object "sq"
sqDelegate sqdele = new sqDelegate(sq.area);
// also can be written as
// sqDelegate sqdele = sq.area; 
// calling 2nd method "perimeter" Multicasting
sqdele += sq.perimeter; 
// pass the values in two method
// by using "Invoke" method
sqdele.Invoke(6.25);
Console.WriteLine();
// call the methods with
// different values
sqdele.Invoke(10.25);
}
}

Output:

Area is: 39.0625

Perimeter is: 25 

 

Area is: 105.0625

Perimeter is: 41 

Now, it’s time to move to FAQs

FAQs

  1. What is a delegate?
    A delegate is a type that represents methods with a specific argument list and return type. 
  2. Why are delegates used?
    Delegates are used to pass methods to other methods as arguments. Event handlers are just methods that are invoked via delegates. We write a custom method that a class, such as a Windows control, may call when an event happens.
  3. Why we can alter methods calls when we use delegates?
    The delegate can be allocated any method from any available class or struct that fits the delegate type. A static method or an instance method can be used. Because of this flexibility, we may alter method calls programmatically or add new code to existing classes.
  4. What is the multicasting of delegates?
    Multiple methods can be pointed to by the delegate. A multicast delegate is a delegate that points to many methods.
  5. How to add or remove components from a multicast delegate?
    Multiple objects can be assigned to a single delegate instance by using the + or += operator, which is a useful feature of multicasting delegate objects. Similarly, to remove a component delegate from a multicast delegate, use the -  or -= operator. 

Now, its time to summarise our learning.

Key Takeaways

In this article, we have extensively discussed C# Delegates. What are delegates was discussed. It’s syntax and then a declaration. Then we discussed its invocation. Then we learnt the multicasting of delegates. We understood all concepts using the programme example. Finally, we discussed FAQs.

Ninjas! Check out our other articles on C# to master your learnings in this.

Multithreading in C#, singleton design pattern in c#

We hope that this blog has helped you enhance your knowledge regarding Delegates in C# and if you would like to learn more, check out our articles on Coding Ninjas Studio. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass