Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What the purpose/difference in using an event-type constructor

Tags:

c#

events

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?

like image 707
hultqvist Avatar asked Jun 07 '10 22:06

hultqvist


People also ask

Why do we use constructors in JavaScript?

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.

What is an event type?

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.

What is the use of event object in HTML?

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.


2 Answers

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.

like image 147
Jon Skeet Avatar answered Oct 01 '22 19:10

Jon Skeet


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.

like image 29
Lasse V. Karlsen Avatar answered Oct 01 '22 20:10

Lasse V. Karlsen