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
Required. Any expression that evaluates to a reference type.
Required. Any data type name.
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 ||Compatibility criterion|
If the run-time type of
objectexpression satisfies the compatibility criterion,
objectexpression is null, then
False, and ...
TypeOf is always used with the
Is keyword to construct a
Is expression, or with the
IsNot keyword to construct a
The following example uses
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)
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.