Blorgbeard
Blorgbeard

Reputation: 103467

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?

Upvotes: 14

Views: 3570

Answers (6)

Andrei Rînea
Andrei Rînea

Reputation: 20790

A little offtopic :

You could instantiate a delegate (new EventHandler(MethodName)) and (if appropriate) reuse that instance.

Upvotes: 2

denis phillips
denis phillips

Reputation: 12770

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.

Upvotes: 5

Timbo
Timbo

Reputation: 28050

Wasn't the new XYZEventHandler require until C#2003, and you were allowed to omit the redundant code in C#2005?

Upvotes: 0

Orion Edwards
Orion Edwards

Reputation: 123652

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

Upvotes: 26

Rob Cooper
Rob Cooper

Reputation: 28867

I think the one way to really tell would be to look at the MSIL produced for the code.. Tends to be a good acid test..

I have funny concerns that it may somehow mess with GC.. Seems odd that there would be all the overhead of declaring the new delegate type if it never needed to be done this way, you know?

Upvotes: -1

Ray
Ray

Reputation: 46585

I don't think there's any difference. Certainly resharper says the first line has redundant code.

Upvotes: 2

Related Questions