Nullable Values and Nothing
Prerequisites: Classes and objects
Nothing means "no value", but it behaves differently for reference
types and value types.
Nothing for reference types
For classes, strings, and arrays, Nothing means "no object":
Module Program
Function FindUser(id As Integer) As String
If id = 1 Then Return "Ada"
Return Nothing
End Function
Sub Main()
Dim user = FindUser(2)
Console.WriteLine(user Is Nothing)
Console.WriteLine(If(user, "(guest)"))
Console.WriteLine(If(user?.ToUpper(), "(no name)"))
Console.WriteLine(String.IsNullOrEmpty(user))
End Sub
End Module
True
(guest)
(no name)
True
- Test with
Is Nothing/IsNot Nothing. If(value, fallback)supplies a default.?.stops and returnsNothingif the left side isNothing.
Nothing for value types: the default value
Assigning Nothing to an Integer, Boolean, or Date doesn't mean
"empty" — it sets the type's default value:
Module Program
Sub Main()
Dim n As Integer = Nothing
Dim b As Boolean = Nothing
Dim d As Date = Nothing
Console.WriteLine(n)
Console.WriteLine(b)
Console.WriteLine(d.Year)
End Sub
End Module
0
False
1
This surprises developers coming from C#, where int x = null doesn't
compile.
Nullable value types
To let a value type be truly "missing", make it nullable with ?
(short for Nullable(Of T)):
Module Program
Sub Main()
Dim age As Integer? = Nothing
Console.WriteLine(age.HasValue)
Console.WriteLine(age.GetValueOrDefault(-1))
Console.WriteLine(If(age, 0))
age = 36
Console.WriteLine(age.HasValue & " " & age.Value)
Dim total As Integer? = age + 1
Console.WriteLine(total)
Dim missing As Integer? = Nothing
Dim sum = missing + 5
Console.WriteLine(sum.HasValue)
End Sub
End Module
False
-1
0
True 36
37
False
Arithmetic with a missing value gives a missing result. Nullable types are common for optional database columns and optional form fields.
Comparing with Nothing
Module Program
Sub Main()
Dim score As Integer? = Nothing
Console.WriteLine(score Is Nothing)
If score > 50 Then
Console.WriteLine("passed")
Else
Console.WriteLine("not passed (or unknown)")
End If
End Sub
End Module
True
not passed (or unknown)
Use Is Nothing to test a nullable value — score = Nothing compares
with a missing value and is never True. A comparison involving a
missing value is treated as False in an If.
Common mistakes
- Calling
.Valueon an empty nullable — it throwsInvalidOperationException. CheckHasValueor useGetValueOrDefault. - Forgetting that a
Stringfield starts asNothing, not"".