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
Is Nothingtests identity against the null reference.?.calls only when the receiver exists; otherwise it yields Nothing.- Two-argument
If(a, b)coalesces: the first non-Nothing wins. Integer?holds a number or Nothing, withHasValueandValue.
Keywords and builtins used here
DimIfIntegerNotNothingStringThen
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.
Step 2 of 3 in VB idioms, step 23 of 29 in Language basics.