Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between wiring events with and without "new"

In C#, what is the difference (if any) between these two lines of code?

tmrMain.Elapsed += new ElapsedEventHandler(tmrMain_Tick);

and

tmrMain.Elapsed += tmrMain_Tick;

Both appear to work exactly the same. Does C# just assume you mean the former when you type the latter?

like image 894
Blorgbeard Avatar asked Aug 25 '08 20:08

Blorgbeard


People also ask

Is it better to use addEventListener or onclick?

addEventListener can add multiple events to a particular element. onclick can add only a single event to an element. It is basically a property, so gets overwritten.

What happens if an event occurs and there is no event handler to respond to the event?

TF: if an event occurs and there is not event handler to respond to that event, the event ins ignored.

What is the difference between event and delegate in C#?

An event is declared using the event keyword. Delegate is a function pointer. It holds the reference of one or more methods at runtime. Delegate is independent and not dependent on events.

What is the benefit of the addEventListener () method?

The addEventListener() method makes it easier to control how the event reacts to bubbling. When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.


2 Answers

I did this

static void Hook1()
{
    someEvent += new EventHandler( Program_someEvent );
}

static void Hook2()
{
    someEvent += Program_someEvent;
}

And then ran ildasm over the code.
The generated MSIL was exactly the same.

So to answer your question, yes they are the same thing.
The compiler is just inferring that you want someEvent += new EventHandler( Program_someEvent );
-- You can see it creating the new EventHandler object in both cases in the MSIL

like image 172
Orion Edwards Avatar answered Oct 01 '22 10:10

Orion Edwards


It used to be (.NET 1.x days) that the long form was the only way to do it. In both cases you are newing up a delegate to point to the Program_someEvent method.

like image 45
denis phillips Avatar answered Oct 01 '22 12:10

denis phillips