How to Unsubscribe from Event in C# - Simple Guide
To unsubscribe from an event in C#, use the
-= operator with the same event handler method you used to subscribe. This removes the handler from the event's invocation list, stopping it from being called when the event fires.Syntax
In C#, you unsubscribe from an event using the -= operator followed by the event handler method. This removes the method from the event's list of subscribers.
eventName: The event you want to unsubscribe from.handlerMethod: The method that was previously subscribed to the event.
csharp
eventName -= handlerMethod;
Example
This example shows how to subscribe and then unsubscribe from an event. The event handler will only run before it is unsubscribed.
csharp
using System; class Program { // Define a delegate for the event public delegate void Notify(); // Define an event based on the delegate public static event Notify OnNotify; static void Main() { // Subscribe the handler OnNotify += HandlerMethod; Console.WriteLine("Raising event first time:"); OnNotify?.Invoke(); // Calls HandlerMethod // Unsubscribe the handler OnNotify -= HandlerMethod; Console.WriteLine("Raising event second time:"); OnNotify?.Invoke(); // No output because handler is removed } static void HandlerMethod() { Console.WriteLine("Event handler called."); } }
Output
Raising event first time:
Event handler called.
Raising event second time:
Common Pitfalls
Common mistakes when unsubscribing from events include:
- Using a different method or anonymous delegate to unsubscribe than the one used to subscribe. This will not remove the handler.
- Unsubscribing from an event that is
nullwithout checking, which can cause aNullReferenceException. - Forgetting to unsubscribe in long-running applications, which can cause memory leaks.
csharp
/* Wrong way: Using a different handler to unsubscribe */ OnNotify += HandlerMethod; OnNotify -= AnotherMethod; // Does NOT unsubscribe HandlerMethod /* Right way: Use the same handler method */ OnNotify -= HandlerMethod;
Quick Reference
Remember these tips when unsubscribing from events:
- Always use the same method to unsubscribe that you used to subscribe.
- Check if the event is not
nullbefore invoking or unsubscribing. - Unsubscribe to avoid memory leaks in long-running apps.
Key Takeaways
Use the -= operator with the same handler method to unsubscribe from an event.
Unsubscribing prevents the handler from being called when the event fires.
Always unsubscribe to avoid memory leaks in long-running applications.
Ensure you unsubscribe the exact same method you subscribed with.
Check for null events before invoking or unsubscribing to avoid errors.