![]() |
VOOZH | about |
Events in C# provide a way for objects to communicate with each other. They are based on the publisher-subscriber model, where one class (publisher) notifies other classes (subscribers) when something of interest occurs. Events are built on top of delegates and form a key part of event-driven programming.
An event is a mechanism for sending notifications from one object to another. It is declared in a class and is triggered when a specific action happens. Events rely on delegates to point to the method that will handle the occurrence.
Syntax for Declaring an Event:
public event EventHandler EventName;
An event handler is a method that responds to an event. It contains the code to be executed when the event is raised. Event handlers are usually void methods with two parameters:
Syntax:
public delegate void EventHandler(object sender, EventArgs e);
EventHandler is a delegate. To subscribe to this event a class must have a method with void return type and two input parameters of types :
A delegate specifies the signature of the event handler methods.
The event is declared in a class using that delegate.
Output:
Process Started...
Process Completed!
Here, the Process class is the publisher and ProcessCompletedHandler is the subscriber. The event is raised once the process finishes.
Instead of defining custom delegates, C# provides EventHandler (no extra data) and EventHandler<TEventArgs> (with custom data). This is the recommended approach.
Output:
Task Running...
Task Completed Event Fired!
Here, TaskCompleted is raised by TaskManager. The handler method Manager_TaskCompleted executes when the event fires.
When you need to pass additional information, create a custom EventArgs class.
Output:
Downloading example.txt...
Download Finished: example.txt
Now the event not only notifies subscribers but also provides useful information (FileName) about the completed download.