*
Previous Delegates in C# LINQ in C# Next

📣 Events in C#

📣 Events in C#

An event in C# is a mechanism that allows a class to notify other classes or objects when something of interest happens. Events are built on top of delegates and follow the publisher-subscriber model.

🧩 Key Concepts

  • Publisher: The class that raises the event.
  • Subscriber: The class that listens and responds to the event.
  • Event Handler: A method that gets called when the event is triggered.

📘 Example: Basic Event

  public class Alarm {
      public event EventHandler AlarmTriggered;

      public void TriggerAlarm() {
          Console.WriteLine("Alarm triggered!");
          AlarmTriggered?.Invoke(this, EventArgs.Empty);
      }
  }

  public class Listener {
      public void OnAlarmTriggered(object sender, EventArgs e) {
          Console.WriteLine("Listener received alarm event.");
      }
  }

  class Program {
      static void Main() {
          Alarm alarm = new Alarm();
          Listener listener = new Listener();

          alarm.AlarmTriggered += listener.OnAlarmTriggered;
          alarm.TriggerAlarm();
      }
  }
  

📚 Types of Events in C#

  • Standard Events: Use EventHandler or EventHandler<T> with EventArgs.
  • Custom Events: Use custom delegate types and custom event argument classes.
  • Multicast Events: Events with multiple subscribers; all handlers are invoked in order.
  • Static Events: Events declared as static and shared across all instances.
  • Interface Events: Events declared in interfaces and implemented by classes.
  • Anonymous Events: Events handled using lambda expressions or anonymous methods.

✅ Best Practices

  • Use EventHandler or EventHandler<T> for consistency.
  • Use ?.Invoke to safely raise events.
  • Unsubscribe from events to avoid memory leaks.
  • Use protected virtual void OnEventName() to raise events.
  • Keep event handlers lightweight and fast.

📌 When to Use

  • In UI applications to respond to user actions.
  • To decouple components in modular systems.
  • For signaling state changes or notifications.
  • In real-time systems where responsiveness matters.

🚫 When Not to Use

  • For tightly coupled logic—use direct method calls instead.
  • In performance-critical paths where event overhead matters.
  • When you need guaranteed synchronous execution order.

⚠️ Precautions

  • Ensure subscribers unsubscribe properly to prevent memory leaks.
  • Handle exceptions inside event handlers to avoid crashing the publisher.
  • Be cautious with multicast events—multiple handlers may affect performance.

🎯 Advantages

  • Loose coupling: Promotes modular and maintainable code.
  • Scalability: Multiple subscribers can respond independently.
  • Flexibility: Subscribers can be added or removed dynamically.
  • Reusability: Event-driven components are easier to reuse.

📝 Conclusion

Events in C# are a powerful mechanism for building responsive, modular, and scalable applications. By leveraging delegates and the publisher-subscriber model, you can create systems that react dynamically to changes and user interactions.

Back to Index
Previous Delegates in C# LINQ in C# Next
*
*