Events in C# Programming
Events in C# are mechanisms that allow a class to notify other classes or objects when something of interest occurs. Events rely on delegates to define and raise notifications.
1. Defining and Raising Events
To define and raise an event, you need a delegate type and an event based on that delegate.
Step-by-Step Example: Defining and Raising Events
using System; // Define a delegate delegate void Notify(string message); // Define a class with an event class EventPublisher { public event Notify OnNotify; public void RaiseEvent(string message) { // Check if there are any subscribers if (OnNotify != null) { OnNotify(message); } } } class Program { static void Main() { EventPublisher publisher = new EventPublisher(); // Subscribe to the event publisher.OnNotify += (msg) => Console.WriteLine("Event raised: " + msg); // Raise the event publisher.RaiseEvent("Hello, Events!"); } }
Output:
Event raised: Hello, Events!
2. Event Handling
Event handling involves subscribing to an event and defining the actions to be performed when the event is triggered.
Step-by-Step Example: Event Handling
using System; // Define a delegate delegate void Notify(string message); // Define a class with an event class Alarm { public event Notify AlarmTriggered; public void TriggerAlarm(string location) { if (AlarmTriggered != null) { AlarmTriggered("Alarm triggered at: " + location); } } } class Program { // Event handler method static void HandleAlarm(string message) { Console.WriteLine(message); } static void Main() { Alarm alarm = new Alarm(); // Subscribe to the event alarm.AlarmTriggered += HandleAlarm; // Raise the event alarm.TriggerAlarm("Server Room"); } }
Output:
Alarm triggered at: Server Room
Key Points
- Events are special delegates designed for one-to-many notifications.
- Events ensure encapsulation by only allowing the event publisher to raise the event.
- Subscribers can register or unregister from events dynamically.
Conclusion
Events in C# are integral to building event-driven and interactive applications. By defining and handling events, developers can create programs that respond dynamically to user actions or system changes.