6

Is there a difference between

Object.Event += new System.EventHandler(EventHandler);
Object.Event -= new System.EventHandler(EventHandler);

AND

Object.Event += EventHandler;
Object.Event -= EventHandler;

? If so, what?

Aren't they both just pointers to methods?

Maxim Gershkovich
  • 45,951
  • 44
  • 147
  • 243
  • possible duplicate of [C# Event handlers](http://stackoverflow.com/questions/26877/c-sharp-event-handlers) – nawfal Jul 06 '14 at 20:49

2 Answers2

6

Both are Exactly same. But

Object.Event += EventHandler;
Object.Event -= EventHandler;

The above example compiles fine only in 3.0 or later version of C#, while if you are in 2.0 or before you can only use following construct.

Object.Event += new System.EventHandler(EventHandler);
Object.Event -= new System.EventHandler(EventHandler);

Look more about at Type inferencing. search for "Type Inference"

crypted
  • 10,118
  • 3
  • 39
  • 52
2

No, they are exactly the same. The second version is purely a shorthand where the compiler creates an instance of the event handler for you. Just like simplified property syntax, using etc ... all compiler magic!

See this related question:

Difference between wiring events using "new EventHandler<T>" and not using new EventHandler<T>"?

Community
  • 1
  • 1
ColinE
  • 68,894
  • 15
  • 164
  • 232