C# - Delegate
Table of Content:
What is delegate?
A delegate in C# is a type that represents references to methods with a particular parameter list and return type. Delegates are used to pass methods as arguments to other methods and can be used to define callback methods. They are similar to function pointers in C and C++, but are type-safe and secure.
Key Features of Delegates
- Type-Safe: Ensures that the signature of the delegate matches the method signature.
- Secure: Allows methods to be encapsulated and passed around.
- Flexible: Can be used to implement event handling and callback methods.
Declaring a Delegate
To declare a delegate, you use the delegate
keyword followed by a method signature.
public delegate int MathOperation(int a, int b);
Instantiating and Using Delegates
You can instantiate a delegate by assigning it a method with a matching signature.
public class Program { // Define a delegate public delegate int MathOperation(int a, int b); // Define methods that match the delegate signature public static int Add(int a, int b) { return a + b; } public static int Multiply(int a, int b) { return a * b; } public static void Main(string[] args) { // Instantiate the delegate with the Add method MathOperation operation = new MathOperation(Add); Console.WriteLine("Add: " + operation(3, 4)); // Output: Add: 7 // Reassign the delegate to the Multiply method operation = new MathOperation(Multiply); Console.WriteLine("Multiply: " + operation(3, 4)); // Output: Multiply: 12 } }
Multicast Delegates
A multicast delegate can hold references to more than one method. When a multicast delegate is invoked, it calls the methods in the order they were added.
public class Program { // Define a delegate public delegate void Notify(); // Define methods that match the delegate signature public static void SendMessage() { Console.WriteLine("Message sent"); } public static void Log() { Console.WriteLine("Log entry created"); } public static void Main(string[] args) { // Instantiate the delegate and add methods Notify notify = SendMessage; notify += Log; // Invoke the multicast delegate notify(); // Output: Message sent // Log entry created } }
Using Delegates with Events
Delegates are often used with events. An event in C# is a mechanism for communication between objects. It allows a class to notify other classes or objects when something of interest occurs.
using System; public class Program { // Define a delegate for the event public delegate void NotifyEventHandler(object sender, EventArgs e); // Define an event based on the delegate public event NotifyEventHandler Notify; // Method to raise the event public void Process() { Console.WriteLine("Process started"); OnNotify(EventArgs.Empty); } // Protected virtual method to allow derived classes to override the event invocation behavior protected virtual void OnNotify(EventArgs e) { Notify?.Invoke(this, e); } public static void Main(string[] args) { Program program = new Program(); // Subscribe to the event program.Notify += Program_Notify; // Start the process program.Process(); } // Event handler method private static void Program_Notify(object sender, EventArgs e) { Console.WriteLine("Process completed"); } }
Summary
- Delegates are type-safe method references.
- Can encapsulate methods and allow them to be passed as parameters.
- Multicast delegates can reference multiple methods.
- Commonly used with events to provide a notification system.