VB.Net: Determine if an Object or Class Implements and 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:

If MyClass Is IMyInterface Then

The Solution

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

If GetType(IMyInterface).IsAssignableFrom(MyClass) Then
    ' Do something interesting, e.g.
    CType(MyObject, IMyInterface).MethodOnIMyInterface()
End If

Or for an object:

 If GetType(IMyInterface).IsAssignableFrom(MyObject.GetType) Then
    ' Do something interesting, e.g.
    CType(MyObject, IMyInterface).MethodOnIMyInterface()
End If

3 Responses to VB.Net: Determine if an Object or Class Implements and Interface

  1. […] Where “CurrentType” is the type from the current assembly that I’m evaluating, and IMyInterface is just that – my custom interface.  I found this gem here: https://allwrong.wordpress.com/2009/06/29/vb-net-determine-if-an-object-or-class-implements-and-inter…. […]

  2. Daniel says:

    You may not be able to use:
    If MyClass Is IMyInterface Then

    However, the following is pretty close and works:
    If TypeOf MyClass Is IMyInterface Then

    This is what I have always used.

Leave a comment