Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

events

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!

like image 276
Ian Avatar asked Mar 29 '11 06:03

Ian


People also ask

How does the event handler handle every event?

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.

What is the advantage of using EventHandler<teventargs>?

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.

Why does vs 2003 emit a new EventHandler around the function name?

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.

How do I create a custom event data class in EventHandler?

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.


1 Answers

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.

like image 100
SWeko Avatar answered Sep 28 '22 05:09

SWeko