Part 5 With TypeOf, all base classes of a variable are also checked, and this means the Is-keyword will return True for Object.
Class Example
Public Dim _name As String = "bird"
End Class
Module Module1
Sub Main()
' Part 1: refer to a new Example instance as an Object.
Dim t As Object = New Example()
' Part 2: use Is-operator with TypeOf to test type.
If TypeOf t Is Example
Console.WriteLine("Is Example")
End If
' Part 3: use IsNot operator with TypeOf.
If TypeOf t IsNot String
Console.WriteLine("IsNot String")
End If
' Part 4: use TryCast to get back to Example type.
Dim e = TryCast(t, Example)
If Not IsNothing(e)
Console.WriteLine($"Name = {e._name}")
End If
' Part 5: TypeOf Is can detect base classes like Object.
If TypeOf e Is Object
Console.WriteLine("Is Object")
End If
End Sub
End ModuleIs Example
IsNot String
Name = bird
Is Object
Summary. Though we cannot use the Is-keyword to directly test the type of a variable, we can use it as part of a TypeOf expression. This allows us to test types (and base types) in VB.NET.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 5, 2024 (edit link).