AnyCompiler

Nullable Types and Null Safety

A plain int can never be null — it always holds some actual number. int? (shorthand for Nullable<int>) adds the possibility of 'no value' on top of int, with .HasValue to check and .Value to read the underlying number once you know it's present.

using System;

class Program {
    static void Main() {
        int? maybeAge = null;
        Console.WriteLine(maybeAge.HasValue);
        maybeAge = 25;
        Console.WriteLine(maybeAge.Value);
    }
}
Output
False
25

?. and ??

?. (null-conditional) accesses a member only if the thing on its left isn't null, short-circuiting to null instead of throwing. ?? (null-coalescing) then supplies a fallback value when the left side turns out to be null.

using System;

class Program {
    static void Main() {
        string name = null;
        Console.WriteLine(name?.Length ?? -1);
    }
}
Output
-1

name?.Length would normally throw a NullReferenceException on a null string if written as name.Length — ?. avoids that entirely, and ?? supplies -1 since there's no length to report.

Next: exceptions and resource cleanup — try/catch/finally, and a closing look at using/IDisposable's deterministic cleanup guarantee.

Practice exercise

Declare int? maybeAge set to null, then print it using ?? to fall back to -1.