TypeOf Operator (Visual Basic)

 

Updated: July 20, 2015

For the latest documentation on Visual Studio 2017, see Visual Studio 2017 Documentation.

Compares an object reference variable to a data type.

  
result = TypeOf objectexpression Is typename  

  
result = TypeOf objectexpression IsNot typename  

result
Returned. A Boolean value.

objectexpression
Required. Any expression that evaluates to a reference type.

typename
Required. Any data type name.

The TypeOf operator determines whether the run-time type of objectexpression is compatible with typename. The compatibility depends on the type category of typename. The following table shows how compatibility is determined.

Type category of typenameCompatibility criterion
Classobjectexpression is of type typename or inherits from typename
Structureobjectexpression is of type typename
Interfaceobjectexpression implements typename or inherits from a class that implements typename

If the run-time type of objectexpression satisfies the compatibility criterion, result is True. Otherwise, result is False. If objectexpression is null, then TypeOf...Is returns False, and ...IsNot returns True.

TypeOf is always used with the Is keyword to construct a TypeOf...Is expression, or with the IsNot keyword to construct a TypeOf...IsNot expression.

The following example uses TypeOf...Is expressions to test the type compatibility of two object reference variables with various data types.

        Dim refInteger As Object = 2
        MsgBox("TypeOf Object[Integer] Is Integer? " & TypeOf refInteger Is Integer)
        MsgBox("TypeOf Object[Integer] Is Double? " & TypeOf refInteger Is Double)
        Dim refForm As Object = New System.Windows.Forms.Form
        MsgBox("TypeOf Object[Form] Is Form? " & TypeOf refForm Is System.Windows.Forms.Form)
        MsgBox("TypeOf Object[Form] Is Label? " & TypeOf refForm Is System.Windows.Forms.Label)
        MsgBox("TypeOf Object[Form] Is Control? " & TypeOf refForm Is System.Windows.Forms.Control)
        MsgBox("TypeOf Object[Form] Is IComponent? " & TypeOf refForm Is System.ComponentModel.IComponent)

The variable refInteger has a run-time type of Integer. It is compatible with Integer but not with Double. The variable refForm has a run-time type of Form. It is compatible with Form because that is its type, with Control because Form inherits from Control, and with IComponent because Form inherits from Component, which implements IComponent. However, refForm is not compatible with Label.

Is Operator
IsNot Operator
Comparison Operators in Visual Basic
Operator Precedence in Visual Basic
Operators Listed by Functionality
Operators and Expressions

Show: