[Gtk-sharp-list] Attaching method to events without explicit EventHandler instanciation

Chris Howie cdhowie at gmail.com
Fri Feb 22 18:06:44 EST 2008


On Thu, Feb 21, 2008 at 12:39 PM, Charles-Henri d'Adhémar
<cdadhemar at gmail.com> wrote:
>  The way a method is attached to an event seems equivalent in class
>  Test1 and Test2 below :
>
>                button1.Clicker += new EventHandler(hello_event);
> [snip]
>                button1.Clicker += hello_event;
>
>  Can a method (in our case hello_event) be attached to a GTK# event
>  without instantiating a delegate (new EventHandler(hello_event); ) ?

Yes and no.

Actually, the two lines of code you have given above will compile to
exactly the same IL sequence.  The ability to "use a method as a
delegate" was added in the C# 2.0 language specification as a way to
save time coding.  The compiler looks at the context to determine the
type it needs (EventHandler in this case) and looks at the right side
and says "this is a method with the same or compatible signature as
that delegate, let's just create the delegate."  It's similar to type
inference in a way.

So there are a few points you have to consider:

1) Implicitly creating the delegate is easier to type and reads better
(in my opinion).

2) Implicitly creating the delegate is *NOT* compatible with C# 1.0.
Note that mcs does support C# 2.0 features that are binary-compatible
with the 1.1 CLI assembly format, which includes features like this
one as well as anonymous delegates and the like.  Microsoft's 1.1
compiler does not, to my knowledge, support anything but C# 1.0 so if
you are targeting the 1.1 framework and would like to be compatible
with the MS 1.1 compiler, you should explicitly create the delegate.
If you are targeting the 2.0 framework then it makes no difference
which you choose in this respect.

3) The compiled assembly is going to be identical either way you do
it, so there is no runtime performance difference or assembly size
difference that will impact your decision.

-- 
Chris Howie
http://www.chrishowie.com
http://en.wikipedia.org/wiki/User:Crazycomputers


More information about the Gtk-sharp-list mailing list