About Lesson
Events:
- An event is a mechanism that enables objects to notify other objects when something of interest happens.
- Events are based on delegates and provide a way to handle and respond to specific occurrences or changes in the program.
- Events follow the publisher-subscriber model, where the object raising the event is the publisher, and the object handling the event is the subscriber.
- Events are declared using the event keyword.
Example:
public class Publisher
{
public event EventHandler MyEvent;
public void RaiseEvent()
{
OnMyEvent(EventArgs.Empty);
}
protected virtual void OnMyEvent(EventArgs e)
{
MyEvent?.Invoke(this, e);
}
}
public class Subscriber
{
public void HandleEvent(object sender, EventArgs e)
{
Console.WriteLine(“Event handled by the subscriber”);
}
}
// Usage:
Publisher pub = new Publisher();
Subscriber sub = new Subscriber();
pub.MyEvent += sub.HandleEvent;
pub.RaiseEvent();
// Output:
// Event handled by the subscriber