14

For example, if these codes:

        Button button1 = new Button();
        // ...
        button1.Click -= button1_Clicked;

are executed before:

        button1.Click += button1_Clicked;

I found no error or exception, but I am wondering if there is any downside here.

If it is safe, why is it allowed to unsubscribe from an event that has never been subscribed?

Setyo N
  • 1,734
  • 1
  • 22
  • 28

1 Answers1

16

I can't find a reference specific to events, but it is documented for the underlying function that events use, Delegate.Remove:

Returns source if value is null or if the invocation list of value is not found within the invocation list of source

So it will be safe at least for events that use implicit accessors.

Custom accessors are a whole other ball of wax, as one could implement the remove block however you want. I would assume people would mimic the implicit behavior, but this isn't enforced.

Cory Nelson
  • 26,928
  • 5
  • 69
  • 103