What does plus equals(+=) operator means here?

Praveen picture Praveen · Feb 7, 2014 · Viewed 40k times · Source

I was working out sample code of Windows phone and often I see statements with += operator.

I know about add assignment operator which does the below operation

+= means a = a + b;  // used for both adding number and string concatenation

But this is new to me

phNumChoseTask = new PhoneNumberChooserTask();
phNumChoseTask.Completed += new EventHandler<PhoneNumberResult>(phoneNumberChooserTask_Completed);

Here how does += works?

Answer

NValchev picture NValchev · Feb 7, 2014

In the current context += means subscribe. In other words it's like you are telling subscribe my method (the right operand) to this event (the left operand), this way, when the event is raised, your method will be called. Also, it is a good practice to unsubscribe (-= from this event, when you have finished your work ( but before you dispose you object ) in order to prevent your method being called and to prevent resource leaks. FMI look here.