2

Possible Duplicate:
Is there an actual difference in the 2 different ways of attaching event handlers in C#?

I've been seeing a lot of code that looks like this:

foo.Drop += new DragEventHandler(fooHandler);

But in the past, I've always done this:

foo.Drop += fooHandler;

Is there a difference between these two syntaxes? If so, is there any advantage to doing it the long way?

Community
  • 1
  • 1
Matthew
  • 28,056
  • 26
  • 104
  • 170
  • 1
    possible duplicate of [Is there an actual difference in the 2 different ways of attaching event handlers in C#?](http://stackoverflow.com/questions/214346/is-there-an-actual-difference-in-the-2-different-ways-of-attaching-event-handlers), [What is the difference between Events with Delegate Handlers and those without?](http://stackoverflow.com/questions/119160/what-is-the-difference-between-events-with-delegate-handlers-and-those-without), [What is the difference between different ways of attaching\detaching event handlers in C#](http://stackoverflow.com/questions/4360451/) – Cody Gray - on strike May 10 '11 at 13:45
  • Definitely a duplicate. Voted to close myself. – Matthew May 10 '11 at 13:52

4 Answers4

3

The second is shorthand for the first; they will compile to indentical IL.

However, the second syntax is new to C# 2.0; C# 1 only supports the first.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

They will both result in the same IL.

So, in answer to your question, no - there is no benefit of using the longer version.

Nathan
  • 6,095
  • 2
  • 35
  • 61
  • You linked to a disambiguation page that suggests MSIL is the "former acronym" of what is now called [CIL](http://en.wikipedia.org/wiki/Common_Intermediate_Language). – Cody Gray - on strike May 10 '11 at 13:48
  • @Cody Gray updated to the more direct link – Nathan May 10 '11 at 13:53
  • I assume it comes from the effort to emphasize that the platform is not fully proprietary. Microsoft has been somewhat encouraging at various times to efforts like the Mono Project. Everyone I know just calls it "IL", myself included. Prevents marketing from interfering with understanding. ;-) – Cody Gray - on strike May 10 '11 at 13:54
  • Good spot - thanks. Answer updated to call it "IL" ;) – Nathan May 10 '11 at 14:03
0

No difference , since .Net 2 and you can use what is called Method Group Conversion which allow you to Register the method name directly to the event without making a delegate Object

Stacker
  • 8,157
  • 18
  • 73
  • 135
0

They are the same, but in the second example, the compiler uses Method Group conversion to infer the delegate type for you. Syntactic sugar...

Matthew Abbott
  • 60,571
  • 9
  • 104
  • 129