C# magic unviels VB.NET equivalent System.EventHandler(Of T)(AddressOf Me.MyHandler)

Topics: Building and extending application blocks, Enterprise Library Core, General discussion
Mar 1, 2007 at 3:58 PM
I was working on converting some C# code to VB.NET down in the Logging block and I ran into a method that was expecting a parameter of type -
System.EventHandler(Of Microsoft.Practices.EnterpriseLibrary.Configuration.Design.ConfigurationNodeChangedEventArgs)

In C# all you need to do is pass a reference to the event handler function, magic...

New System.EventHandler(Of ConfigurationNodeChangedEventArgs)(AddressOf Me.OnFormatterNodeRemoved)

I can live with that, don't understand exactly why the languages differ so here. But anyway, my point is this got me thinking about 2.0, 3.0 architecture in general. In the .NET framework 2.0, with the advent of generics this technique became possible. Does this techinque simply promote type safety or are their other benefits? Is this technique being used in EntLib based on capablities or requirements of ObjectBuilder with respect to delegates? I found so little documentation of event handling techniques using generics, this is why I ask.
Mar 5, 2007 at 3:54 AM
C# and VB.NET syntax differ here because, historically, VB.NET has tried to hide the concept of delegate from its users. C#, on the other hand, has always put delegates front and center.

As for why this particular generic is used, it prevents proliferation of delegate type definitions. In .NET 1.x, every time you wanted to declare an event that took a custom eventargs type, you needed to define a separate delegate for that event. You ended up with tons of delegates that only differ in the eventargs types.

With generics in 2.0, you can collapse all those separate delegate definitions into one EventHandler<T>, and save the effort of defining (and naming!) all those other delegates.
Mar 5, 2007 at 2:53 PM
I'm going to be coding my own event handler delegates in this manner. Very slick imho.