Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between the following ways to register to event

Tags:

c#

.net

c#-3.0

I would like to register to some event. The following ways works:

public void AddOptionAsListner(OptionElement option)
    {
        option.Selected += onOptionSelectedChanged;
    }

public void AddOptionAsListner(OptionElement option)
    {
        option.Selected += new EventHandler(onOptionSelectedChanged);
    }

Is there a difference or that this is just different syntax for the same thing?

like image 310
Elad Avatar asked Dec 18 '22 06:12

Elad


1 Answers

Same - No diff. The compiler infers the type of delegate and does it auto-magically for you. Syntactic sugar to make your life a bit easier

Just checked with C#-in depth. This feature is called "Method group conversions" ; added in C#2.0

e.g. from the book

static void MyMethod() { ... }
static void MyMethod( object sender, EventArgs e) {...}

static void Main() {
    ThreadStart x = MyMethod;  // binds to first overload
    EventHandler y = MyMethod; // binds to second overload
}

If I open this up in reflector, you'd see that the compiler just created the delegate instances of the right type for you, behind the scenes of course.

    L_0000: ldnull 
    L_0001: ldftn void CS.Temp.Program::MyMethod()
    L_0007: newobj instance void [mscorlib]System.Threading.ThreadStart::.ctor(object, native int)
    L_000c: pop 
    L_000d: ldnull 
    L_000e: ldftn void CS.Temp.Program::MyMethod(object, class [mscorlib]System.EventArgs)
    L_0014: newobj instance void [mscorlib]System.EventHandler::.ctor(object, native int)
    L_0019: pop 
like image 108
Gishu Avatar answered Dec 19 '22 21:12

Gishu