
How can you use the VB.NET Is and IsNot operators to check reference types? With Is and IsNot, you can check reference types against special value such as Nothing, as we demonstrate in this quick example.
This VB tutorial shows how to use the Is and IsNot operators.
In the .NET Framework, we usually compare reference types to Nothing (null) or use member functions. Therefore, the Is and IsNot operators are most often used with the Nothing constant in VB.NET. In this example, we see how IsNot Nothing and Is Nothing are evaluated with a local variable. This pattern of code is useful if you are not sure the variable is set to something before you need to use it.
Program that uses Is and IsNot operators [VB.NET]
Module Module1
Sub Main()
Dim value As String = "cat"
' Check if it is NOT Nothing.
If value IsNot Nothing Then
Console.WriteLine(1)
End If
' Change to Nothing.
value = Nothing
' Check if it IS Nothing.
If value Is Nothing Then
Console.WriteLine(2)
End If
' This isn't reached now.
If value IsNot Nothing Then
Console.WriteLine(3)
End If
End Sub
End Module
Output
1
2
The Is and IsNot operators can only be used with reference types. The Nothing constant is considered a special instance of a reference type. Unlike the C# language, you cannot use the Is operator to perform casting that returns a Boolean in VB.NET.
We looked at the Is and IsNot operators in the VB.NET language. These are most commonly used with the Nothing constant, although any two references can be compared. The result depends on the memory locations, not the object data the references point to.
VB.NET Tutorials