Delegates in C# Programming
A delegate in C# is a type-safe object that points to a method. Delegates allow methods to be passed as parameters and are used to implement event handling and callback methods.
1. Declaring and Using Delegates
To use a delegate, you need to declare it, assign a method to it, and invoke the method through the delegate.
Step-by-Step Example: Declaring and Using Delegates
using System; // Declare a delegate delegate void DisplayMessage(string message); class Program { // Method to be assigned to the delegate static void ShowMessage(string message) { Console.WriteLine("Message: " + message); } static void Main() { // Instantiate the delegate DisplayMessage display = ShowMessage; // Call the method using the delegate display("Hello, Delegates!"); } }
Output:
Message: Hello, Delegates!
2. Multicast Delegates
A multicast delegate can point to multiple methods. When invoked, it calls all the methods in its invocation list in order.
Step-by-Step Example: Multicast Delegates
using System; // Declare a delegate delegate void Notify(string message); class Program { // Methods to be assigned to the delegate static void NotifyByEmail(string message) { Console.WriteLine("Email notification: " + message); } static void NotifyBySMS(string message) { Console.WriteLine("SMS notification: " + message); } static void Main() { // Instantiate the delegate Notify notify = NotifyByEmail; // Add another method to the delegate notify += NotifyBySMS; // Call the methods using the multicast delegate notify("Your order has been shipped!"); // Remove a method from the delegate notify -= NotifyByEmail; // Call the remaining method notify("Your order is out for delivery!"); } }
Output:
Email notification: Your order has been shipped!
SMS notification: Your order has been shipped!
SMS notification: Your order is out for delivery!
Key Points
- Delegates provide flexibility and reusability by allowing methods to be passed as parameters.
- Multicast delegates enable multiple methods to be executed with a single delegate invocation.
- Delegates are commonly used in event handling and asynchronous programming.
Conclusion
Delegates in C# are powerful tools for implementing callback functions and event-driven programming. By mastering delegates and multicast delegates, you can write more flexible and modular code.