Nothing. An object may not exist. A reference may point to nothing. We use the literal Nothing to indicate a null, nil, nonexistent object.
Nothing details. We assign to Nothing, test against it, and ponder nothingness. A NullReferenceException is caused by accessing something on a Nothing value.
First example. This program assigns a String variable to Nothing. This is not an empty string. It is a String object that does not exist. We compare it to Nothing in an If-statement.
Part 1 We use the "Is" operator for testing references against Nothing. Using "=" can give incorrect results.
Part 2 We use the IsNothing function to see if a reference is equal to Nothing. This is another syntax form for the same thing.
' This reference equals Nothing.
Dim s As String = Nothing' Part 1: directly test against Nothing.
If s Is Nothing Then
' Part 2: use the IsNothing function.
If IsNothing(s) Then
NullReferenceException. This exception (not NothingReferenceException) is provoked by accessing a member on Nothing. If a reference may be Nothing, we must test before using its members.
' Assign a String to Nothing.
Dim s As String = Nothing' This causes a NullReferenceException.
Dim len As Integer = s.Length
' Not reached.
End ModuleUnhandled Exception: System.NullReferenceException:
Object reference not set to an instance of an object.
Module. When a Module or Class is created, the fields within it are automatically set to Nothing. You never need to assign them to Nothing at creation time.
Tip Variables in VB.NET never have garbage values. In managed code, like the .NET Framework, initial values are 0 or Nothing.
''' A module-level field.
Dim s As StringBuilder
' The field is nothing when the program begins.
If IsNothing(s) Then
Values. Nothing can be used with value types such as Integers. When used on values, "Nothing" indicates the default value for the type. So an Integer assigned to Nothing is zero.
Tip Structures are too a value type. When we assign them to Nothing, we get an empty Structure (with no bits set to 1).
' Initialize an Integer to Nothing.
Dim size As Integer = Nothing' It equals zero.
If size = 0 Then
Console.WriteLine("Size is 0")
If size = Nothing Then
Console.WriteLine("Size is nothing")
Size is 0Size is nothing
String.IsNullOrEmpty. A string in VB.NET can be assigned to Nothing, which is the same concept as Null. We can test a Nothing String with the String.IsNullOrEmpty method.