Delegates and Calling Functions in C#
What are Delegates?
A delegate in C# is a type that holds references to methods. It is often described as a type-safe function pointer. Delegates are used to pass methods as arguments to other methods.
Why Use Delegates?
Delegates allow you to define callback methods and enable methods to be passed as parameters. They are commonly used in event handling, where one method can be called in response to an event.
Example: Calling Add Function Through Delegates
In this example, we create a delegate that refers to an Add
function and then use the delegate to call the method.
Example Code:
// Define a delegate
public delegate int Operation(int x, int y);
// Method that matches the delegate signature
public static int Add(int a, int b)
{
return a + b;
}
public static void Main(string[] args)
{
// Create an instance of the delegate
Operation operation = Add;
// Call the method through the delegate
int result = operation(5, 10);
// Display the result
Console.WriteLine($"Result after calling Add function through delegates: {result}");
}
In this example, the delegate Operation
holds a reference to the Add
method. When we call operation(5, 10)
, it invokes the Add
method, and the result is displayed.
Key Characteristics of Delegates
- Delegates are type-safe and ensure that the method signature matches the delegate signature.
- Delegates can be used to encapsulate method references and pass methods as arguments.
- A delegate can refer to multiple methods using multicast delegates.
Multicast Delegates
A delegate can reference multiple methods at once. When invoked, all the methods are called in the order they were added.
Example of Multicast Delegates:
// Define a delegate
public delegate void Notify();
// Methods that match the delegate signature
public static void NotifyByEmail()
{
Console.WriteLine("Notification sent by Email");
}
public static void NotifyBySMS()
{
Console.WriteLine("Notification sent by SMS");
}
public static void Main(string[] args)
{
// Create an instance of the delegate and add multiple methods
Notify notify = NotifyByEmail;
notify += NotifyBySMS;
// Call the delegate, which will invoke both methods
notify();
}
In this example, the delegate Notify
holds references to both NotifyByEmail
and NotifyBySMS
. When the delegate is invoked, both methods are called.
Key Points to Remember
- Delegates can reference methods and allow methods to be passed as parameters.
- A delegate is type-safe and ensures that only methods matching the delegate signature can be referenced.
- Multicast delegates can reference and invoke multiple methods.