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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 5, 2024 (edit link).