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
  • 43,966
  • 43
  • 139
  • 233
  • 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
  • 9,848
  • 2
  • 38
  • 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
  • 66,765
  • 14
  • 157
  • 225