VB.Net: Determine if an Object or Class Implements an Interface

The Problem

You want to know if a class called MyClass implements interface IMyInterface, or the object myObject inplements interface IMyInterface.

Unfortunately, you can’t do:

[sourcecode language="vb"]
If MyClass Is IMyInterface Then
    ' Something...
End If
[/sourcecode]

The Solution

It isn’t exactly intuitive, but for a class you can do this:

[sourcecode language='vb']
If GetType(IMyInterface).IsAssignableFrom(MyClass) Then
    ' Do something interesting, e.g.
    CType(MyObject, IMyInterface).MethodOnIMyInterface()
End If
[/sourcecode]

Or for an object:

[sourcecode language='vb']
If GetType(IMyInterface).IsAssignableFrom(MyObject.GetType) Then
    ' Do something interesting, e.g.
    CType(MyObject, IMyInterface).MehodOnIMyInterface()
End If
[/sourcecode]
Be Sociable, Share!
This entry was posted in VB.Net. Bookmark the permalink.

One Response to VB.Net: Determine if an Object or Class Implements an Interface

  1. Pingback: Who’s on first? AppDomains, Pre-loaded Assemblies, and CreateInstanceAndUnwrap « Mark Gilbert’s Blog

Leave a Reply

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