9️⃣ C# Advanced Concepts
Estimated reading: 3 minutes 27 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸš€ C# Events

Or Copy Link

CONTENTS
Scroll to Top