π 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
orEventHandler<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 :