Glossary / Nullable value types
Nullable value types
A nullable value type T? represents every value of a non-nullable value type T plus the absence of a value. It is shorthand for Nullable<T> and is commonly used for optional database fields, measurements, or inputs where a default value would be ambiguous.
Values, tests, and operators
int? score = null;
int display = score ?? 0;
if (score is int actual) Console.WriteLine(actual);
A nullable value type has HasValue and Value; reading Value when absent throws InvalidOperationException, so prefer pattern matching, GetValueOrDefault, or ?? when appropriate. Lifted operators generally propagate null: arithmetic involving a null nullable operand produces null, and nullable comparisons have defined behavior that differs from SQL three-valued logic. bool? has true, false, and null; use explicit patterns or ?? to define policy.
Boxing a nullable with a value boxes the underlying value; boxing an empty nullable produces a null reference. Nullable value types cannot be nested or used for reference types; nullable reference annotations are a separate compiler feature.
Engineering guidance
Use null to represent genuine absence, not as an error sentinel when richer result types are clearer. Convert deliberately at database/serialization boundaries and account for DBNull or schema rules separately. Avoid repeated .Value access without proof of presence.
Interview questions
- What is
int??Nullable<int>, which can represent an integer or no value. - What happens when accessing empty
.Value? It throwsInvalidOperationException. - How does
??help? Provides a fallback when the nullable is absent. - How does nullable boxing work? A present value boxes as the underlying type; empty boxes to null.
- Is
string?the same feature? No; nullable reference types are annotations/analysis, notNullable<T>wrappers.