The Problem Solver

Tell me and I will forget
Show me and I will remember
Involve me and I will understand
- Confucius -

Google Ads

This Blog

Syndication

Search

Tags

News





  • View Maurice De Beijer's profile on LinkedIn

Community

Email Notifications

Explore

Archives

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 Smile
 
In VB we don't have the same thing, the parameters must match exactly. So the following piece of code doesn’t work Sad
 
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 Smile. 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!
 
Published Thu, Feb 8 2007 13:00 by Maurice
Filed under: ,