Events in C#: An Easy-to-Understand Guide

18 Apr 2024

In C#, an event is a mechanism that allows a class or object to notify other classes or objects when something happens. It is essentially a way of implementing the observer design pattern.

Here's a Basic Breakdown of How Events Work in C#:

Declaration of the Event:

An event is declared using the event keyword followed by a delegate type. This delegate type defines the signature of the event handler method that will be called when the event is raised.

Declaration of the Event: Syntax

public event EventHandler MyEvent;

Subscription of the Event:

Other classes or objects can subscribe to the event by adding event handler methods to the event.

Subscription of the Event: Syntax

instance.MyEvent += SomeMethod; // Subscribe

Raising the Event:

The class that declares the event can raise it, typically within a method or property setter where the appropriate conditions are met.

Raising the Event: Syntax

if (MyEvent != null) { MyEvent(this, EventArgs.Empty); }

Event Handler:

The event handler method is a method that matches the signature of the delegate type associated with the event. This method will be invoked when the event is raised.

Event Handler: Syntax

void SomeMethod(object sender, EventArgs e) { // Handle the event }


Subscribed event handlers can be unsubscribed from the event.

Unsubscription: Syntax

instance.MyEvent -= SomeMethod; // Unsubscribe

Event in C# With Example

using System; public class Program { public class EventPublisher { // Define an event delegate public event EventHandler<CustomEventArgs> CustomEvent; // Method to raise the event public void RaiseEvent() { OnCustomEvent(new CustomEventArgs("Event raised!")); } // Method to invoke the event protected virtual void OnCustomEvent(CustomEventArgs e) { CustomEvent?.Invoke(this, e); } } public class CustomEventArgs : EventArgs { public string Message { get; } public CustomEventArgs(string message) { Message = message; } } public class EventSubscriber { public void HandleEvent(object sender, CustomEventArgs e) { Console.WriteLine($"Event handled: {e.Message}"); } } public static void Main(string[] args) { EventPublisher publisher = new EventPublisher(); EventSubscriber subscriber = new EventSubscriber(); // Subscribe to the event publisher.CustomEvent += subscriber.HandleEvent; // Raise the event publisher.RaiseEvent(); // Unsubscribe from the event publisher.CustomEvent -= subscriber.HandleEvent; } }


Event handled: Event raised!

In This Above Example:

  • EventPublisher defines an event named CustomEvent of type EventHandler.

  • EventPublisher also has a method RaiseEvent() which raises the CustomEvent.

  • CustomEventArgs is a custom class derived from EventArgs which contains additional data to be passed along with the event.

  • EventSubscriber has a method HandleEvent() which serves as the event handler.

  • In the Main method, an instance of EventPublisher and EventSubscriber is created.

  • The HandleEvent method of EventSubscriber is subscribed to the CustomEvent event of the CustomEvent EventPublisher.

  • The RaiseEvent() method is called on the EventPublisher triggering the event and invoking the HandleEvent method in EventSubscriber.

  • Finally, the HandleEvent method is unsubscribed from the CustomEvent.

Why Use Event in C#

Events are widely used in C# for implementing various patterns such as the observer pattern, implementing callbacks, and handling user interface interactions in GUI applications. They provide a way for objects to communicate without needing to have direct knowledge of each other. In C#, events are used to implement the observer design pattern, also known as the publish-subscribe pattern.

They provide a way for objects to communicate and react to changes or actions that occur in other objects without needing to have direct knowledge of each other.

Events are extensively used in user interface programming (e.g., Windows Forms, WPF, ASP.NET) to handle user interactions such as button clicks, mouse movements, and keyboard inputs. Events help in decoupling components of an application. Publishers (objects that raise events) do not need to know about the subscribers (objects that handle events), and vice versa

Events enable extensibility by allowing new event handlers to be added without modifying existing code. This makes it easier to add new functionalities or behaviors to an application without having to modify the existing codebase.

Where Use Event in C#

User Interface (UI) Programming: Events are extensively used in UI programming frameworks like Windows Forms, WPF (Windows Presentation Foundation), ASP.NET, Xamarin, and others. Examples include handling button clicks, mouse movements, keyboard inputs, and other user interactions.

Asynchronous Programming: Events are used in asynchronous programming to notify subscribers when asynchronous operations are completed. This is common in scenarios such as handling the completion of asynchronous I/O operations, asynchronous processing in multi-threaded applications, or handling events in asynchronous event-driven programming models.

Observer Design Pattern: Events are often used to implement the Observer design pattern, where an object (the subject or publisher) maintains a list of dependent objects (observers or subscribers) and notifies them of changes in its state. This pattern is widely used in scenarios such as event-driven architectures, GUI programming, and reactive programming.

Custom Event Handling: Developers define custom events in their classes to provide a way for other objects to respond to specific actions or state changes. For example, a class representing a data model might raise events when data is updated, allowing other components to react accordingly.

Delegates and Callbacks: Events are frequently used in conjunction with delegates and callback functions to provide a mechanism for callback-based programming, where one object calls a method on another object in response to some event or condition.

Decoupling Components: Events are used to decouple components in an application, enabling loosely coupled architecture. This allows components to interact without having direct dependencies on each other's implementations, leading to better modularity, maintainability, and extensibility.

Logging and Monitoring: Events are often used for logging and monitoring purposes in applications to record significant events, errors, or exceptions for debugging, analysis, or audit trail purposes.

For more useful tutorials, please visit the site: C-Sharp Tutorial