9️⃣ C# Advanced Concepts
Estimated reading: 3 minutes 334 views

C# Events – Implement Reactive Programming with Delegates


Introduction – Why Events Matter in C#

Events in C# allow your application to react to actionsβ€”such as a button click, a file change, or a data update. Built on the delegate system, events are fundamental to event-driven programming and are widely used in frameworks like Windows Forms, WPF, and ASP.NET.

In this guide, you’ll learn:

  • What events are and how they work
  • How to declare, raise, and subscribe to events
  • The relationship between events and delegates
  • Best practices and use cases

Core Concept – What Are Events?

An event is a message sent by an object to signal that something has happened. It is typically implemented using a delegate, which defines the method signature for event handlers.

Real-life analogy: A doorbell (event) rings (is raised), and the listener (handler) reacts by opening the door.


Event Syntax and Structure

Step 1: Define a Delegate

public delegate void Notify();  // No parameters, no return value

Step 2: Declare an Event

public event Notify OnProcessCompleted;

Step 3: Raise the Event

if (OnProcessCompleted != null)
    OnProcessCompleted();  // Invoke the event

Code Example – Basic Custom Event

using System;

class Process
{
    public delegate void ProcessCompletedHandler();
    public event ProcessCompletedHandler ProcessCompleted;

    public void Start()
    {
        Console.WriteLine("Processing...");
        // Simulate process
        ProcessCompleted?.Invoke();  // Raise event
    }
}

class Program
{
    static void Main()
    {
        Process process = new Process();
        process.ProcessCompleted += () => Console.WriteLine("Process finished!");

        process.Start();
    }
}

Output:

Processing...
Process finished!

Events with EventHandler

C# provides a predefined delegate called EventHandler and its generic version EventHandler<TEventArgs>.

Example Using EventHandler:

public event EventHandler ProcessCompleted;

Using EventArgs:

public class MyEventArgs : EventArgs
{
    public string Message { get; set; }
}

public event EventHandler<MyEventArgs> ProcessCompleted;

This is the preferred .NET pattern, especially for frameworks.


Tips, Pitfalls & Best Practices

Tip: Use ?.Invoke() to raise events safely (null-check in one line).

Pitfall: Failing to unsubscribe (-=) from events may cause memory leaks in long-lived applications.

Best Practice: Always define events using EventHandler or EventHandler<T> for consistency and IDE support.


Real-World Use Cases

  • UI Events: Button clicks, key presses (WinForms, WPF)
  • File Watchers: File system changes (e.g., FileSystemWatcher)
  • Timers: Executing code after time intervals
  • Custom Business Events: OrderPlaced, UserLoggedIn, DataLoaded, etc.

Summary – Recap & Next Steps

Events allow objects to communicate in a loosely coupled way. They make programs interactive, modular, and maintainable.

Key Takeaways:

  • Events are based on delegates and enable reactive programming
  • Use EventHandler or EventHandler<T> for .NET convention
  • Subscribe using +=, unsubscribe using -=
  • Safely raise events with ?.Invoke()

Next: Learn about delegates and lambda expressions for flexible event subscriptions.


FAQ – C# Events

What is the difference between a delegate and an event?
A delegate is a method signature container. An event is a delegate that can only be triggered by the defining class.

How do I unsubscribe from an event?
Use -= like this: myObject.MyEvent -= MyHandler;.

Can an event have multiple subscribers?
Yes. Events support multicast, so many methods can handle the same event.

What’s the best way to raise an event safely?
Use the null-conditional operator: MyEvent?.Invoke(args);.

Should I use EventHandler or custom delegates?
Prefer EventHandler or EventHandler<T> for standardized event patterns in .NET.


Share Now :
Share

πŸš€ C# Events

Or Copy Link

CONTENTS
Scroll to Top