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!
Every event is an action and that event is properly handled by the eventhandler. We create an instance for the delegate and call it when required, the delegate instance points towards the eventhandler method.
The advantage of using EventHandler<TEventArgs> is that you do not need to code your own custom delegate if your event generates event data. You simply provide the type of the event data object as the generic parameter.
Prior to .NET 2.0, every variable assignments must be of exact type, compilers then didn't infer much. So as to make a work-around, VS 2003 emit new EventHandler around the function name. That's just my guess.
The EventHandler delegate includes the EventArgs class as a parameter. When you want to create a customized event data class, create a class that derives from EventArgs, and then provide any members needed to pass data that is related to the event.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With