C#
events
event handlers
programming
.NET

Understanding events and event handlers in C

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Understanding events and event handlers in C# is crucial for building responsive and interactive applications. Events and event handlers are first-class citizens in C#'s object-oriented programming model, facilitating a versatile mechanism for implementing the observer pattern. This article will cover the fundamentals, including the declaration and handling of events in C#, complete with examples and a summary table for quick reference.

What are Events?

Events are special delegates that are specifically used to notify users of your program when something of interest happens. These are integral to the Windows Forms or ASP.NET frameworks, where user actions like button clicks trigger events.

Basic Concepts

  • Publisher: This is the object that holds the event and sends the notification.
  • Subscriber: It is the object that receives the notification and handles the event.
  • Event Handler: A method that is invoked whenever an event is raised.

Syntax

In C#, an event is declared using the event keyword, followed by a delegate type. Here’s a basic example:

csharp
1// Declare the delegate type.
2public delegate void EventHandler(string message);
3
4// Publisher class.
5public class Publisher
6{
7    // Declare the event using the delegate.
8    public event EventHandler OnEventOccurred;
9
10    public void DoSomething()
11    {
12        OnEventOccurred?.Invoke("An event has occurred!");
13    }
14}

Event Handling

Subscribing to Events

To use events effectively, you need to subscribe to them, which entails adding an event handler. Here is how you can subscribe to an event:

csharp
1public class Subscriber
2{
3    public void HandleEvent(string message)
4    {
5        Console.WriteLine(message);
6    }
7}
8
9class Program
10{
11    static void Main()
12    {
13        Publisher publisher = new Publisher();
14        Subscriber subscriber = new Subscriber();
15
16        // Subscribing to the event.
17        publisher.OnEventOccurred += subscriber.HandleEvent;
18
19        // Trigger the event.
20        publisher.DoSomething();
21    }
22}

Unsubscribing from Events

It’s a good practice to unsubscribe from events that are no longer needed, especially since failing to do so can lead to memory leaks. Unsubscribing is done using the -= operator:

csharp
// Unsubscribe from the event.
publisher.OnEventOccurred -= subscriber.HandleEvent;

Advanced Concepts

Event Arguments

Sometimes, you may need to pass more information than just a string when an event occurs. This is where EventArgs comes in handy. Subclass EventArgs to define your custom event data:

csharp
1public class CustomEventArgs : EventArgs
2{
3    public int EventNumber { get; }
4
5    public CustomEventArgs(int eventNumber)
6    {
7        EventNumber = eventNumber;
8    }
9}
10
11// Update the delegate to use the custom event args.
12public delegate void CustomEventHandler(object sender, CustomEventArgs e);
13
14// Modify the event signature in the Publisher class.
15public event CustomEventHandler OnCustomEventOccurred;
16
17public void TriggerCustomEvent()
18{
19    OnCustomEventOccurred?.Invoke(this, new CustomEventArgs(123));
20}

Anonymous Methods and Lambda Expressions

You can also use anonymous methods or lambda expressions to handle events without explicitly defining a separate method:

csharp
1// Using an anonymous method.
2publisher.OnEventOccurred += delegate(string message) {
3    Console.WriteLine("Anonymous method: " + message);
4};
5
6// Using a lambda expression.
7publisher.OnEventOccurred += (message) => Console.WriteLine("Lambda: " + message);

Thread Safety

When working with events, one should consider thread safety. It is recommended to use the null-conditional operator ?., which safely invokes the event handlers if they are subscribed:

csharp
OnEventOccurred?.Invoke("Thread-safe invocation");

Summary Table

Here is a summary of key points about events and event handlers in C#:

ConceptDescription
EventA message sent by an object to signal the occurrence of an action.
DelegateA type that defines the signature of event handlers.
Event HandlerA method that is called when an event occurs.
SubscriptionThe process of registering an event handler with an event. Achieved using +=.
UnsubscriptionDetaching an event handler from an event. Achieved using -=.
EventArgs ClassBase class for classes containing event data.
Thread SafetyEnsure safe event invocation in multithreaded contexts using the ?. operator.

Understanding and properly utilizing events and event handlers in C# can greatly enhance the responsiveness of your applications. By understanding these concepts, you can implement effective communication between components in your C# applications.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.