C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Caution: You may get unexpected results when using "=" and Nothing. For reference types, please use "Is".
Then: We use the IsNothing function to see if a reference is equal to Nothing. This is another syntax form for the same thing.
VB.NET program that tests against Nothing
Module Module1
Sub Main()
' This reference equals Nothing.
Dim s As String = Nothing
' We can directly test against Nothing.
If s Is Nothing Then
Console.WriteLine("1")
End If
' We can use the IsNothing function.
If IsNothing(s) Then
Console.WriteLine("2")
End If
End Sub
End Module
Output
1
2
VB.NET program that causes NullReferenceException
Module Module1
Sub Main()
' Assign a String to Nothing.
Dim s As String = Nothing
' This causes a NullReferenceException.
Dim len As Integer = s.Length
' Not reached.
Console.WriteLine(len)
End Sub
End Module
Output
Unhandled Exception: System.NullReferenceException:
Object reference not set to an instance of an object.
Tip: Variables in VB.NET never have garbage values. In managed code, like the .NET Framework, initial values are 0 or Nothing.
VB.NET program that uses module-level field
Imports System.Text
Module Module1
''' <summary>
''' A module-level field.
''' </summary>
Dim s As StringBuilder
Sub Main()
' The field is nothing when the program begins.
If IsNothing(s) Then
Console.WriteLine(True)
End If
End Sub
End Module
Output
True
Tip: Structures are too a value type. When we assign them to Nothing, we get an empty Structure (with no bits set to 1).
VB.NET program that uses values, Nothing
Module Module1
Sub Main()
' Initialize an Integer to Nothing.
Dim size As Integer = Nothing
' It equals zero.
Console.WriteLine(size)
If size = 0 Then
Console.WriteLine("Size is 0")
End If
If size = Nothing Then
Console.WriteLine("Size is nothing")
End If
End Sub
End Module
Output
0
Size is 0
Size is nothing
Tip: The term "null" is simply a different name for "Nothing." There is no "IsNothingOrEmpty" string method.
VB.NET program that uses String.IsNullOrEmpty
Module Module1
Sub Main()
Dim value As String = Nothing
' Nothing is the same as "Null."
If String.IsNullOrEmpty(value) Then
Console.WriteLine("NULL OR EMPTY")
End If
End Sub
End Module
Output
NULL OR EMPTY
Note: Thanks to Matthieu Penant for pointing out that Nothing has a separate meaning on value types.
Quote: In Visual Basic, if you set a variable of a non-nullable value type to Nothing, the variable is set to the default value for its declared type.
Nothing: Microsoft Docs