How to Subscribe to Event in C#: Simple Guide
In C#, you subscribe to an event using the
+= operator followed by a method that matches the event delegate signature. This method will be called automatically when the event is raised.Syntax
To subscribe to an event, use the += operator with the event name and a method that handles the event. The method must match the event delegate's signature.
- eventName: The event you want to listen to.
- handlerMethod: The method that runs when the event occurs.
csharp
eventName += handlerMethod;
Example
This example shows how to subscribe to a simple event and handle it by printing a message.
csharp
using System; class Publisher { public event EventHandler? OnChange; public void RaiseEvent() { OnChange?.Invoke(this, EventArgs.Empty); } } class Subscriber { public void HandleEvent(object? sender, EventArgs e) { Console.WriteLine("Event received and handled."); } } class Program { static void Main() { Publisher pub = new Publisher(); Subscriber sub = new Subscriber(); // Subscribe to the event pub.OnChange += sub.HandleEvent; // Trigger the event pub.RaiseEvent(); } }
Output
Event received and handled.
Common Pitfalls
Common mistakes when subscribing to events include:
- Not matching the handler method signature with the event delegate.
- Forgetting to unsubscribe from events, which can cause memory leaks.
- Using
=instead of+=, which replaces existing handlers instead of adding.
csharp
/* Wrong: Replaces existing handlers */ pub.OnChange = sub.HandleEvent; // Use += instead /* Correct: Adds handler without removing others */ pub.OnChange += sub.HandleEvent;
Quick Reference
Remember these tips when subscribing to events in C#:
- Use
+=to add event handlers. - Handler methods must match the event delegate signature.
- Unsubscribe with
-=when no longer needed. - Use
?.Invoketo safely raise events.
Key Takeaways
Subscribe to events using the += operator with a matching handler method.
Always match the handler method signature to the event delegate.
Avoid replacing handlers by using = instead of +=.
Unsubscribe from events with -= to prevent memory leaks.
Use ?.Invoke to safely raise events without null errors.