Checking an objects type or implemented interfaces

A common thing people might want to do is check if a object is a certain type, or inherits a type, or implements a type.

This can be done in VB.Net with the following code:

TypeOf someObject Is ClassName

This works for inheritance heirarchy as well as checking for interface implementation.

Here is a sample app showing it in practice.

imports Microsoft.VisualBasic
imports System
Imports System.Collections.Generic

public module MyModule
    sub Main
dim o as new subclass
        WL(typeof o is subclass)
        WL(typeof o is baseclass)
        WL(typeof o is IWhatever)
    end sub

    #region "Helper methods"

    sub WL(text as object)
    end sub

    sub WL(text as object, paramarray args as object())
        Console.WriteLine(text.ToString(), args)
    end sub
    sub RL()
    end sub
    sub Break()
    end sub

#end region

end module

public interface IWhatever
end interface
public class BaseClass

end class

public class SubClass
inherits BaseClass
implements IWhatever

end class

Leave a Reply

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

You are commenting using your 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