How to use delegates in C#

Delegates

Delegates in C# are similar to function pointers in C++– they are variables that store references to methods. Delegates can store references to any method of the same return type and parameters.

Some variance is allowed in delegates that point to methods with slightly different type signatures. This may include types that are ancestors to or inherited by those in the delegate’s type signatures.

Delegate variables can also be multi-casted. Multi-casted delegate variables call one function after another. The + operator is used to multi-cast functions, and the - is used to remove a function from the multi-casted variables’ list of execution.

svg viewer

Usage

The following example demonstrates how delegates are used.

using System;
class DelegateExample
{
// Delegates defined
public delegate int delFunc(int num);
public delegate void delFunc2();
public static int doubleNum(int num)
{
return num + num;
}
public static int squareNum(int num)
{
return num * num;
}
public static void function1(){
Console.Write("Hello, ");
}
public static void function2(){
Console.Write("World!");
}
static void Main()
{
// Delegate variables declared
delFunc fun1 = new delFunc(doubleNum);
delFunc fun2 = new delFunc(squareNum);
delFunc2 multiFun;
// Multi-casting delegate variable
multiFun = new delFunc2(function1);
multiFun += new delFunc2(function2);
// Calling doubleNum(3) using delegate
Console.WriteLine(fun1(3));
// Calling squareNum(3) using delegate
Console.WriteLine(fun2(3));
// Calling function1() and then function2() using delegate
multiFun();
}
}

In this example, two delegates, delFunc and delFunc2, are defined. delFunc takes an integer as a parameter and returns an integer. delFunc2 takes no parameter and returns nothing.

Two methods with matching signatures (with delFunc, doubleNum and, squareNum) are defined, referenced to by delegate variables fun1 and fun2, and then called using these variables.

Similarly, two functions matching delFunc2, function1, and function2 are defined. A delFunc2 delegate variable is initialized, multicasted to call function1 and function2, and then used to invoke these functions. This call outputs, “Hello, World!” to the terminal, with the “Hello,” in function1 and the “World!” in function2.

Free Resources

HowDev By Educative. Copyright ©2025 Educative, Inc. All rights reserved