user7009415 user7009415 - 1 month ago 24
C# Question

C# -= operator to unsubscribe from a single event multiple times

In C# 5, what is the behavior of the -= operator when unsubscribing from events.

Assume subscribing to the same event multiple times is valid for this application logic, such as follows:

Property_Saved += Property_Saved_Handler;
Property_Saved += Property_Saved_Handler;
Property_Saved += Property_Saved_Handler;


Now we are subscribed three times.

After unsubscribing with the following one line of code:

Property_Saved -= Property_Saved_Handler;


How many subscriptions are left? 2? none? ...?

Answer

Two after left after that - each -= only removes one subscription. At least, that's the case if it's using just a regular delegate to back the event.

You can see this easily without really involving events:

using System;

public class Program
{
    public static void Main(string[] args)
    {
        Action action = () => Console.WriteLine("Foo");
        // This is a stand-in for the event.
        Action x = null;
        x += action;
        x += action;
        x += action;
        x -= action;
        x(); // Prints Foo twice
    }
}

Strictly speaking, an event subscription could do anything. You could implement an event like this:

private EventHandler weirdEvent;
public event EventHandler WeirdEvent
{
    add { weirdEvent += value; } // Subscribe as normal
    remove { weirdEvent = null; } // I'm bored with *all* the handlers
}

But normally events just delegate to Delegate.Combine and Delegate.Remove, which are the methods that += and -= are syntactic sugar for in C#.

My article on events and delegates contains more details about exactly what happens with combination and removal.