6

What's the difference between the two?

object.ProgressChanged += new EventHandler<ProgressChangedEventArgs>(object_ProgressChanged)

object.ProgressChanged += object_ProgressChanged;

    void installableObject_InstallProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        EventHandler<ProgressChangedEventArgs> progress = ProgressChanged;
        if (installing != null)
            installing(this, e);
    }

EDIT:

If there are no difference, which is the better choice?

Thanks!

Ian
  • 5,625
  • 11
  • 57
  • 93
  • 1
    The first is longer then the other ... – Stefan Steinegger Mar 29 '11 at 06:50
  • 1
    This question has been answered before. http://stackoverflow.com/questions/2749868/new-eventhandlermethod-vs-method – Joel Lee Mar 29 '11 at 06:55
  • 1
    possible duplicate of [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) – Oliver Mar 29 '11 at 06:56
  • possible duplicate of [Should I instantiate a new delegate or not?](http://stackoverflow.com/questions/4676399/should-i-instantiate-a-new-delegate-or-not) – nawfal Jul 06 '14 at 20:15

4 Answers4

6

Basically, one is shorter than the other. It's just synctactic sugar.

The "correct" syntax is the first one, as ProgresChanged is an EventHandler event, so for you to assign a actual handler to it, you need to create a new EventHandler object, whose constructor takes as a parameter the name of a method with the required signature.

However, if you just specify the name of the method (second syntax), an instance of the eventHandler class is created implicitly, and that instance is assigned to the ProgressChanged event.

I prefer using the second method because it's shorter, and does not lose any information. There are not much contexts where you could mistake a += methodName construct for something else.

SWeko
  • 30,434
  • 10
  • 71
  • 106
5

No difference. The same ilcode is generated.

As for which one is better: I use the second options since it's cleaner code = easier to read.

jgauffin
  • 99,844
  • 45
  • 235
  • 372
3

No difference. The second one will be implicitely converted to the first by the compiler.

Henrik
  • 23,186
  • 6
  • 42
  • 92
0

There is no difference between the two, they are same. In fact, the latter is just a shortcut and it will be compiled like the former.

Riana

Riana
  • 689
  • 6
  • 22