Reputation: 18461
In all examples I can find as well as the automatically generated code i Visual Studio, events are set using the following code:
button1.Click += new System.EventHandler(this.button1_Click);
But I can also write it visually cleaner by omitting the constructor wrapper:
button1.Click += this.button1_Click;
Which also compile fine.
What is the difference between these two? And why is the first one mostly used/preferred?
Upvotes: 5
Views: 118
Reputation: 942000
It is removing event handlers that inspired the sugar:
button1.Click -= new System.EventHandler(this.button1_Click);
Using new to remove an event handler? Yes.
Even the full delegate constructor syntax is sugar. A delegate needs a Method and a Target. The target is automatically assigned without you specifying it. It will be "this". A bit unfortunate, it hides the fact that an event subscription adds a reference to your class object that can keep it from being garbage collected. It is explicit in the C++/CLI syntax:
button1->Click += gcnew System::EventHandler(this, &button1_Click);
with the interesting twist that you could actually subscribe an event handling method of another object or class. Not that this gets a lot of use.
Upvotes: 2
Reputation: 391456
The second one is syntactic sugar that expands to the first one, through compiler magic.
The first one might be preferred because the event type isn't hidden from the code, and thus might be easier to read later on, but functionally (and IL-wise) they're the same.
Upvotes: 2
Reputation: 1502036
The second form (implicit conversion from a method group to a delegate type) wasn't supported before C# 2, so any tutorials etc written before 2005 would have used the first form.
Also, IIRC Visual Studio auto-completes the first form. Personally I prefer the second.
Upvotes: 5