C# why does assigning an event handler use a += operator and not =

100 views Asked by At

Maybe I'm not googling hard enough, but I'd like to understand the syntax '+=' when assigning an event. For example we use:

myButton.Click += MyClickEvent;

rather than:

myButton.Click = MyClickEvent;

Why is this the case? Is there some maths going on here? Why would you add addresses?

1

There are 1 answers

0
Connor Stoop On BEST ANSWER

An event can have more than one handler, so it is not a assignment but a subscription.
You could do the following and all handlers would be called.

myButton.Click += MyClickEvent;
myButton.Click += MyClickEvent1;
myButton.Click += MyClickEvent2;

To unsubscribe from the event use

myButton.Click -= MyClickEvent2;