Udostępnij za pośrednictwem


TypeOf Operator (Visual Basic)

Compares an object reference variable to a data type.

result = TypeOf objectexpression Is 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.

TypeOf is always used with the Is keyword to construct a TypeOf...Is 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

Concepts

Comparison Operators in Visual Basic

Operators and Expressions in Visual Basic

Reference

Is Operator (Visual Basic)

IsNot Operator

Operator Precedence in Visual Basic

Operators Listed by Functionality