[Gtk-sharp-list] Attaching method to events without explicit EventHandler instanciation
Charles-Henri d'Adhémar
cdadhemar at gmail.com
Sat Feb 23 05:06:00 EST 2008
Thank you very much Chris for your very clear explanations (are you a
teatcher or something ;-) )
I am targeting a .Net 2.0 frawework essentially with mono and gmcs.
I agree with you about using implicit delegate creation and will use
this syntax in the futur.
Thank you again for your support !
Cheers,
Chicha
2008/2/23, Chris Howie <cdhowie at gmail.com>:
> 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