In C#, a delegate represents a reference to a method. It allows us to store references to methods, pass them as arguments to other methods, and invoke them dynamically at runtime. Delegates are a fundamental feature of C# and are commonly used for implementing event handling and callbacks.
Delegates are crucial in programming for implementing callback mechanisms, event handling, and achieving loose coupling between components. They enhance code flexibility and extensibility, supporting asynchronous programming and dynamic method invocations in real-world applications.
Delegates are declared using the delegate
keyword, followed by the delegate signature, which specifies the method’s return type and parameter types, as shown below:
delegate int MyDelegate(int a, int b);
In this example, we define a delegate named MyDelegate
using the delegate
keyword. This delegate is designed to return an int
, and take two parameters, a
and b
.
Delegates are reference types, and we can create instances of delegates that reference specific methods with compatible signatures as follows:
int AddNumbers(int a, int b);MyDelegate myDelegateInstance = AddNumbers;
Note: We can assign a method to a delegate instance if the method has a compatible signature with the delegate. In the example above, AddNumbers
should have the signature int AddNumbers(int a, int b)
, which is compatible with MyDelegate
.
In this example, we define a function named AddNumbers
that returns an int
and takes two parameters, a
and b
. Then, we create a MyDelegate
instance named myDelegateInstance
and assign AddNumbers
to it.
using System;class Program{// Define a delegate named MyDelegate with the same signature as AddNumbersdelegate int MyDelegate(int a, int b);// Create a method that matches the delegate signaturestatic int AddNumbers(int a, int b){return a + b;}static void Main(string[] args){// Create an instance of MyDelegate and assign the AddNumbers method to itMyDelegate myDelegateInstance = AddNumbers;// Use the delegate to call the AddNumbers methodint result = myDelegateInstance(5, 7);Console.WriteLine("Result: " + result); // Output: Result: 12}}
In this code, we define the MyDelegate
delegate, create a AddNumbers
method that matches the delegate’s signature and then assign the AddNumbers
method to an instance of the delegate. Finally, we use the delegate to call the AddNumbers
method, which returns the sum of two numbers.
Delegates can reference multiple methods, allowing us to invoke multiple methods sequentially using a single delegate instance. This is known as a multicast delegate. To add more function instances, we must use the +=
operator. Let’s understand this with the help of the example.
using System;class Program{// Define a delegate named MyDelegate with the same signature as AddNumbersdelegate void MyDelegate(int a, int b);// Create a method that matches the delegate signaturestatic void AddNumbers(int a, int b){Console.WriteLine("Result of Additon " + (a + b)) ;}static void SubtractNumbers(int a, int b){Console.WriteLine("Result of Subtractio " + (a - b)) ;}static void Main(string[] args){// Create an instance of MyDelegate and assign the AddNumbers method to itMyDelegate multicastDelegate = AddNumbers;multicastDelegate += SubtractNumbers; // Now it references both AddNumbers and SubtractNumbers// Use the delegate to call the AddNumbers methodmulticastDelegate(5, 7);}}
Line 6: We define a delegate named MyDelegate
with the same signature as AddNumbers
and SubtractNumbers
.
Lines 9–17: We define two methods, AddNumbers
and SubtractNumbers
, each taking two integer parameters, performing relevant operations, and printing their value using the Console.WriteLine
function.
Line 21: We create an instance of the MyDelegate
delegate called multicastDelegate
and assign the AddNumbers
method to it. This means the multicastDelegate
now references the AddNumbers
method.
Line 22: We use the +=
operator to assign SubtractNumbers
to the multicastDelegate
. With the help of the multicastDelegate
we can call two methods using single delegates.
Line 23: We call the multicastDelegate
instance.
Note: In multicast delegates, multiple methods are invoked using a single delegate instance.
We can invoke a delegate using the ()
operator, passing arguments if the delegate signature expects them.
Note: C# supports defining methods inline using anonymous methods or lambda expressions. These can be assigned to delegates directly without explicitly defining a separate method.
using System;namespace Program{delegate int MathOperation(int a, int b); // Define a delegate typeclass EducativeCalculator{static int AddNumbers(int a, int b) // Create AddNumbers with compatible signatures{return a + b;}static int SubtractNumbers(int a, int b) // Create SubtractNumbers with compatible signatures{return a - b;}static void Main(string[] args){// Create delegate instances and assign methodsMathOperation add = AddNumbers;MathOperation sub = SubtractNumbers;int result1 = add(10, 5); // Invokes the Add methodint result2 = sub(10, 5); // Invokes the Subtract methodConsole.WriteLine("Addition Result: " + result1);Console.WriteLine("Subtraction Result: " + result2);}}}
Line 6: We define the delegate
type named MathOperation
. This delegate type has a signature that matches methods that take two integers as parameters and b
return an int
. We use this delegate to reference methods with compatible signatures.
Lines 10–18: We define the AddNumbers
and SubtractNumbers
methods. These methods match the signature of the MathOperation
delegate, meaning they can be assigned to the delegate instances of the MathOperation
type.
Lines 20–24: Inside the Main
method, we create the delegate instances, add
and sub
, and assign the AddNumbers
and SubtractNumbers
methods, respectively. This means that the add
instance now references the AddNumbers
method, and the sub
instance references the SubtractNumbers
method.
Lines 26–30: We use the delegate instances add
and sub
to invoke the methods they reference. In result1
, the add
delegate invokes the AddNumbers
method with arguments 10
and 5
, resulting in the addition operation (10 + 5). In result2
, the sub
delegate invokes the SubtractNumbers
method with the same arguments, performing the subtraction operation (10 - 5).
Free Resources