Skip to content
March 8, 2011 / pauldundon

Detecting Event Handlers in VB.NET

The Problem: You have a class which exposes events and want to detect whether any other class has registered handlers for them. Although this is trivial in C#, VB provides no way to do this directly.

Possible Solution: You can use reflection to find and inspect the delegate list for an event. This technique relies on internal details of the CLR, however, so there is a (slim) chance that some future release of .NET will break it. (The following code assumes you’ve imported System.Reflection; the name parameter is the name of the event)

    
Public Function IsEventHandled(ByVal item As Object, ByVal name As String) As Boolean
    Return Not item.GetType.GetField(name & "Event",
                                                BindingFlags.NonPublic Or
                                                BindingFlags.Instance).GetValue(item) Is Nothing
End Function
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: