Relaxed delegates in Visual Basic 8

In C# they have a thing called relaxed delegates that allow you to create an event handler with all parameter types as object and still be able to bind them to an event. Nice [:)]

 

In VB we don’t have the same thing, the parameters must match exactly. So the following piece of code doesn’t work [:(]

 

Imports System.Reflection
Imports System.Windows.Forms
 
Module Module1
 
    Sub Main()
        Dim demo AsNew EventDemo
        demo.HookEvent()
        demo.FireEvent()
    EndSub
EndModule
 
 
PublicClass EventDemo
    Private _textBox AsNew TextBox
 
    PublicSub HookEvent()
        AddHandler _textBox.TextChanged, AddressOf MyEventHandler
    EndSub
 
    PublicSub FireEvent()
        _textBox.Text = “Some text”
    EndSub
 
    Sub MyEventHandler(ByVal sender AsObject, ByVal e AsObject)
        Console.WriteLine(“Event fired, sender = ‘{0}’, e = ‘{1}'”, sender.GetType().FullName, e.GetType().FullName)
    EndSub
EndClass

 

So is there no way to use a generic event handler with all parameters defined as object? Actually there is, its just a bit harder to do. Change the HookEvent to the following and it will work just fine:

 

PublicSub HookEvent()
    Dim eventInfo As EventInfo
    Dim methodInfo As MethodInfo
    Dim dlg As [Delegate]
    eventInfo = _textBox.GetType().GetEvent(“TextChanged”)
    methodInfo = Me.GetType().GetMethod(“MyEventHandler”)
    dlg = [Delegate].CreateDelegate(eventInfo.EventHandlerType, Me, methodInfo)
    eventInfo.AddEventHandler(_textBox, dlg)
EndSub

 

Not exactly the prettiest way of doing it but when you need to it will work [:)]. Lets just hope that relaxed delegates make their way into VB 9 so we can just use the AddHandler syntax, after all it is so much cleaner.

 

Enjoy!

 


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>