Reputation: 4948
Please I want to know the difference between these two. I often use this +=
for events like
this.btnExport.Click += new System.EventHandler(this.btnExport_Click);
From time to time, I do come across sometimes I do come across some declarations like below.
this.cmbClient.SelectedIndexChanged -= new System.EventHandler(this.cmbClient_SelectedIndexChanged);
I try checking for what the differences are on msdn yet couldn't find a source. Please any help or clarification would be appreciated.
Upvotes: 0
Views: 98
Reputation: 1503439
Simply put, +=
subscribe a handler to the event, and -=
unsubscribes a handler from the event. (If the specified handler isn't an existing subscriber, the attempt is ignored.)
Note that you can use significantly simpler syntax as of C# 2:
this.btnExport.Click += this.btnExport_Click;
This uses a method group conversion to convert this.btnExport_Click
into an EventHandler
.
How the event implements subscription and unsubscription is up to the implementation. Often it's just a matter of using Delegate.Combine
and Delegate.Remove
, but it doesn't have to be. Fundamentally, an event is a bit like a property - except instead of get
and set
functionality, it has add
and remove
; using +=
on an event calls the add
part, and using -=
calls the remove
part.
See my article on delegates and events for more details.
Upvotes: 4
Reputation: 6427
The += will register the event hander to the event.
The -= will unregister the event handler from the event.
Upvotes: 2