Search code examples
c#eventscompound-assignment

C# Compound Assignment (e.g. +=, -=, etc.) "Exceptions"


I'm reading a book on C#, and it has this to say about compound assignments (e.g. +=, -=, *=, /=, <<=, >>=):

A subtle exception to this rule is with events, which we describe in Chapter 4: the += and -= operators here are treated specially and map to the event's add and removed accessors.

Can anyone explain what that means in plain English? I'm not to Chapter 4 yet.


Solution

  • Normally a += would add the expression/variable on the right hand side to the one on the left and assign the result to the left hand side.

    // if a = 4, after this statement, a would be 5
    a += 1;
    

    But in case the left hand side of the expression with a += is an event, then this is not the case, but it would be the event handler on the right hand side, which is added to the list of event handlers for that event.

    // whereas on the below statement someEventHandler is added to the collection of event handlers for the 'OnSomeEvent' event
    self.OnSomeEvent += someEventHandler