TypeOf Operator (Visual Basic)

Checks whether the runtime type of an expression's result is type-compatible with the specified type.

Syntax

result = TypeOf objectexpression Is typename  
result = TypeOf objectexpression IsNot typename  

Parts

result
Returned. A Boolean value.

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

typename
Required. Any data type name.

Remarks

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 typename Compatibility criterion
Class objectexpression is of type typename or inherits from typename
Structure objectexpression is of type typename
Interface objectexpression 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.

Example

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.

See also