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?
A constructor enables you to provide any custom initialization that must be done before any other methods can be called on an instantiated object. The ValidationError class doesn't need an explicit constructor, because it doesn't need to do any custom initialization.
An event type is a data structure that defines the data contained in an event. When raw event data comes into the Oracle Event Processing application, the application binds that data to an event of a particular event type.
When a W3C event listener's event occurs and it calls its associated function, it also passes a single argument to the function—a reference to the event object. The event object contains a number of properties that describe the event that occurred.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With