21

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?

Praveen
  • 55,303
  • 33
  • 133
  • 164

4 Answers4

23

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.

NValchev
  • 2,855
  • 2
  • 15
  • 17
8

The += operator is used to specify a method that will be called in response to an event; such methods are called event handlers. The use of the += operator in this context is referred to as subscribing to an event.

Other usage, It can also be used as assignment operator:

a=a+b;

can be written as

 a+=b;
Venkatesh K
  • 4,364
  • 4
  • 18
  • 26
3

It is creating a delegate (pointer) to phoneNumberChooserTask_Completed and adding it to Completed's list of "Event Handlers".

The -= will remove an event handler from the event.

Note: Delegates perform the same way at events, so you can have multiple assignments to either a delegate or event, and when the delegate or event is executed, all assignments will be executed.

Farhad Jabiyev
  • 26,014
  • 8
  • 72
  • 98
0

Here it means that 'attaching (or lets say assigning) a new event handler' to phNumChoseTask. you can detach it also by '-=' programmatically.

Waqas Shabbir
  • 755
  • 1
  • 14
  • 34