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
Advertisements

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 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: