A nullable value type, written int?, lets a value type hold null as well as its normal values. It is shorthand for Nullable<int>, a struct with a HasValue flag and a Value property.
It fits data that can be missing, like a database column that allows NULL or an optional form field.
Check HasValue before reading Value, because reading Value when it holds nothing throws an InvalidOperationException. The ?? operator supplies a fallback instead, and GetValueOrDefault() returns the type's default.
int? nullableInt = null;
bool? nullableBool = null;
// Checking for null
if (nullableInt.HasValue)
{
int value = nullableInt.Value;
}
// Null coalescing operator
int result = nullableInt ?? 0; // Use 0 if null
Do not confuse these with nullable reference types like string?, which are compile-time annotations only.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓