Sunday, May 15, 2005

Events as Delegates under the Hood

Delegates in C# vs VB.NET down to the IL is a good post by Tobin Titus comparing how event handlers are implemented in VB and C# and explaing the underlying IL generated by both. The VB apparently uses a virtual dispatch method under the hood. It uses the "little know feature ... event accessors" to facilitate the handles construct.

Did you catch the difference between the C# and VB.NET IL output? We are no
longer calling ldvirtftn, but instead, we are simply calling ldftn. This is the
difference between VB.NET using a virtual dispatch sequence and C# using an
instance dispatch sequence. ... My guess is that if you don't understand delegates, you won't get the difference between these two fields.

He references C# language docs at MSDN which discusses "field-like events"

When compiling a field-like event, the compiler automatically creates
storage to hold the delegate, and creates accessors for the event that add or
remove event handlers to the delegate field.

I must admit that I miss the VB handlers when I write C#. I don't like having to look in the generated code section to see the tie ups. Tobin suggests the C# approach is more OOP. Maybe so, but less obvious.

Tobin Titus has been among the authors of multiple books (mostly Wrox) on .NET threading and related topics. He is joining MS on the IIS team.

[Factored out of a moved post - Jan 2006]

0 Comments:

Post a Comment

<< Home