How to: Determine Whether Two Objects Are Related (Visual Basic)

You can compare two objects to determine the relationship, if any, between the classes from which they are created. The IsInstanceOfType method of the System.Type class returns True if the specified class inherits from the current class, or if the current type is an interface supported by the specified class.

To determine if one object inherits from another object's class or interface

  1. On the object you think might be of the base type, invoke the GetType method.

  2. On the System.Type object returned by GetType, invoke the IsInstanceOfType method.

  3. In the argument list for IsInstanceOfType, specify the object you think might be of the derived type.

    IsInstanceOfType returns True if its argument type inherits from the System.Type object type.

Example

The following example determines whether one object represents a class derived from another object's class.

Public Class baseClass
End Class
Public Class derivedClass : Inherits baseClass
End Class
Public Class testTheseClasses
    Public Sub seeIfRelated()
        Dim baseObj As Object = New baseClass()
        Dim derivedObj As Object = New derivedClass()
        Dim related As Boolean
        related = baseObj.GetType().IsInstanceOfType(derivedObj)
        MsgBox(CStr(related))
    End Sub
End Class

Note the unexpected placement of the two object variables in the call to IsInstanceOfType. The supposed base type is used to generate the System.Type class, and the supposed derived type is passed as an argument to the IsInstanceOfType method.

See also