22

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?

3
  • Why would you expect it not to be? Commented Sep 5, 2014 at 3:30
  • It does not really make sense to me that we could unsubscribe from something before we subscribe to it first.
    – Setyo N
    Commented Sep 5, 2014 at 3:35
  • 2
    Fair enough, but consider a List<T>. If you call list.Remove(new T()), it won't throw an exception. At most, you'll get a return value of false from most C# collection types. Commented Sep 5, 2014 at 3:43

1 Answer 1

22

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.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.