typestar

Nothing and Nullable in Visual Basic

Nothing checks, ?. chains and If() — VB's null-safety kit.

Dim nickname As String = Nothing
Console.WriteLine(nickname Is Nothing)
Console.WriteLine($"length: {nickname?.Length}")

Dim fallback = If(nickname, "anonymous")
Console.WriteLine(fallback)

Dim price As Integer? = Nothing
If Not price.HasValue Then price = 25
Console.WriteLine(price.Value)

Dim discount As Integer? = Nothing
Console.WriteLine($"you save {If(discount, 0)}")

How it works

  1. Is Nothing tests identity against the null reference.
  2. ?. calls only when the receiver exists; otherwise it yields Nothing.
  3. Two-argument If(a, b) coalesces: the first non-Nothing wins.
  4. Integer? holds a number or Nothing, with HasValue and Value.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
377
Tokens
80
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 60 seconds.

Type this snippet

Step 2 of 3 in VB idioms, step 23 of 29 in Language basics.

← Previous Next →