In C#, delegates and events are two powerful features that allow you to implement the observer pattern, which allows an object to notify other objects when something interesting happens.
Here are some of the key concepts related to delegates and events in C#:
1. Delegates: A delegate is a type that represents a reference to a method with a particular signature. A delegate can be thought of as a function pointer or a callback function.
Here is an example of a delegate in C#:
public delegate void MyDelegate(int x, int y);
This code defines a delegate type named “MyDelegate” that takes two integer parameters and has a void return type. Any method that matches this signature can be assigned to a variable of type “MyDelegate”.
2. Events: An event is a mechanism for notifying other objects when something interesting happens. An event is declared using the “event” keyword and is associated with a delegate.
Here is an example of an event in C#:
public class Button { public event EventHandler Click; public void OnClick() { Click?.Invoke(this, EventArgs.Empty); } }
This code defines a “Button” class with an event named “Click” that is associated with the “EventHandler” delegate. The “OnClick” method raises the “Click” event by invoking the delegate with the “this” object and an empty “EventArgs” object.
3. Subscribing to events: To subscribe to an event, you use the += operator to add a method to the event’s invocation list. The method must match the signature of the delegate associated with the event.
Here is an example of subscribing to an event in C#:
Button myButton = new Button(); myButton.Click += MyButton_Click; private void MyButton_Click(object sender, EventArgs e) { Console.WriteLine("Button clicked!"); }
This code creates a “Button” object and subscribes to its “Click” event by adding the “MyButton_Click” method to the invocation list. When the button is clicked, the “MyButton_Click” method will be called and will print a message to the console.
4. Unsubscribing from events: To unsubscribe from an event, you use the -= operator to remove a method from the event’s invocation list.
Here is an example of unsubscribing from an event in C#:
myButton.Click -= MyButton_Click;
This code removes the “MyButton_Click” method from the invocation list of the “Click” event of the “myButton” object.
Delegates and events are powerful tools in C# that allow you to create flexible and maintainable code. By using delegates and events, you can implement the observer pattern and create objects that can notify other objects when something interesting happens.