Skip to content
Codescope

Nullable value types & null safety

int? is a struct; nullable reference types are a compiler promise.

core8 min6 steps

Before you start

A regular int cannot be null — it always holds a number. But real data has gaps: a database field that might be NULL, an optional config value, a form input someone left blank.

C# gives you two answers. int? (nullable value type) is a real struct that wraps the int with a "do I have a value?" flag — a runtime construct. string? (nullable reference type) is a compiler annotation only, telling the checker "this might be null", with zero runtime cost.

This lesson visualises both, and shows the ?? and ?. operators that make working with maybe-null values a lot less painful.

Stack

nullable value types are structs with a flag
Main()
xint
42
4 bytes

int cannot be null. The type guarantees a value exists.

Step 1 of 6. int always has a value. `int x = 42` stores 42. You cannot assign `null` to an `int` — the compiler rejects it. A value type always contains a value. But sometimes "no value" is a legitimate state: a database field that can be NULL, an optional configuration setting. That is what `int?` is for.

01 / 06

Step 01 / 06

int always has a value

int x = 42 stores 42. You cannot assign null to an int — the compiler rejects it. A value type always contains a value.

But sometimes "no value" is a legitimate state: a database field that can be NULL, an optional configuration setting. That is what int? is for.

nullable-types.csC#
int  x = 42;       // always has a valueint? y = null;     // Nullable<int> — may be absentint? z = 7;// Check before useif (y.HasValue)    Console.WriteLine(y.Value);// Null-coalescing: default if nullint safe = y ?? 0;              // 0// Null-conditional: short-circuit on nullstring? name = null;            // nullable reference typeint? len = name?.Length;        // null, no exception// Pattern matchingstring Describe(int? n) => n switch {    null      => "absent",    < 0       => "negative",    0         => "zero",    int val   => $"positive: {val}"};