|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
TypeOf Operator (Visual Basic)
Compares an object reference variable to a data type.
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|
objectexpression is of type typename or inherits from typename
objectexpression is of type typename
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.
TypeOf is always used with the Is keyword to construct a TypeOf...Is 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. It is compatible with Form because that is its type, with because Form inherits from Control, and with because Form inherits from , which implements IComponent. However, refForm is not compatible with .