" rather than using the new EventHandler "? What is the difference between the two...">

Difference between posting events using "new EventHandler <T>" rather than using the new EventHandler <T> "?

What is 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 is no difference, is this the best choice?

Thanks!

+6
c # events
source share
4 answers

In principle, one is shorter than the other. It is just syntactic sugar.

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

However, if you simply provide a method name (second syntax), an instance of the eventHandler class is created implicitly, and this instance is assigned to the ProgressChanged event.

I prefer to use the second method because it is shorter and does not lose any information. There are not many contexts where you could take the += methodName construct for something else.

+6
source share

No difference. The same code is called.

As for the best: I use the second option, since it is cleaner code = easier to read.

+5
source share

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

+3
source share

There is no difference between them, they are the same. In fact, the latter is just a shortcut, and it will be compiled as the first.

Riana

0
source share

All Articles