How to: Determine What Type an Object Variable Refers To (Visual Basic)
An object variable contains a pointer to data that is stored elsewhere. The type of that data can change during run time. At any moment, you can use the GetTypeCode method to determine the current run-time type, or the TypeOf Operator to find out if the current run-time type is compatible with a specified type.
To determine the exact type an object variable currently refers to
Dim myObject As Object myObject.GetType()
Dim myObject As Object Dim datTyp As Integer = Type.GetTypeCode(myObject.GetType()) MsgBox("myObject currently has type code " & CStr(datTyp))
You can test the TypeCode enumeration value against whichever enumeration members are of interest, such as
To determine whether an object variable's type is compatible with a specified type
TypeOfoperator in combination with the Is Operator to test the object with a
If TypeOf objA Is System.Windows.Forms.Control Then MsgBox("objA is compatible with the Control class") End If
Trueif the object's run-time type is compatible with the specified type.
The criterion for compatibility depends on whether the specified type is a class, structure, or interface. In general, the types are compatible if the object is of the same type as, inherits from, or implements the specified type. For more information, see TypeOf Operator.
Compile the code
Note that the specified type cannot be a variable or expression. It must be the name of a defined type, such as a class, structure, or interface. This includes intrinsic types such as