How to: Determine What Type an Object Variable Refers To
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 (Visual Basic) 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
On the object variable, call the GetType method to retrieve a System.Type object.
Dim myObject As Object myObject.GetType()
On the System.Type class, call the shared method GetTypeCode to retrieve the TypeCode enumeration value for the object's type.
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 Double.
To determine whether an object variable's type is compatible with a specified type
Use the TypeOf operator in combination with the Is Operator (Visual Basic) to test the object with a TypeOf...Is expression.
If TypeOf objA Is System.Windows.Forms.Control Then MsgBox("objA is compatible with the Control class") End If
The TypeOf...Is expression returns True if 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 (Visual Basic).
Compiling 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 Integer and String.
See Also
Concepts
Object Variables in Visual Basic