Nullable Types and Nothing

14.1 Nothing

Nothing means null for reference types and the default value for value types (Dim i As Integer = Nothing gives 0).

Dim s As String = Nothing
If s Is Nothing Then Console.WriteLine("no string")
If String.IsNullOrEmpty(s) Then Console.WriteLine("null or empty")

14.2 Nullable Value Types

⚠️ Comparisons with a nullable Nothing value produce Nothing, which If treats as False. Use .HasValue checks for clarity.

Dim age As Integer? = Nothing             ' Nullable(Of Integer)
Dim score As Nullable(Of Double) = 95.5
If age.HasValue Then Console.WriteLine(age.Value)
Console.WriteLine(age.GetValueOrDefault(18))
Dim displayAge = If(age, 0)               ' coalesce: 0 if Nothing
Dim sum = age + 5                         ' Nothing (null propagation)
If age = 30 Then ...                      ' Nothing = 30 evaluates to Nothing (treated as False)

14.3 Null-Conditional and Null-Safe Patterns

Dim city = customer?.Address?.City                    ' Nothing if any part is Nothing
Dim count = orders?.Count                              ' Integer?
Dim firstName = names?(0)
RaiseEvent Changed(Me, EventArgs.Empty)               ' RaiseEvent is already null-safe
callback?.Invoke(result)
Dim display = If(customer?.Name, "Unknown")
ArgumentNullException.ThrowIfNull(customer)           ' .NET 6+ guard