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?
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
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