Glossary / Nullable reference types
Nullable reference types
Nullable reference types (NRT) add compile-time annotations and flow analysis to express whether a reference is intended to be null. string means “should be non-null” and string? means “may be null” in an enabled nullable context, but both are the same CLR runtime type; NRT do not add runtime null checks.
Nullable context and flow state
Enable with <Nullable>enable</Nullable> or directives. The compiler tracks a variable's null state through checks and assignments, warning when maybe-null values are dereferenced or assigned to non-nullable locations. if (x is not null) narrows within its flow scope; ! suppresses a warning and asserts the author's belief without checking. #nullable disable and oblivious legacy annotations can weaken analysis.
Annotations also affect public API metadata and are consumed by callers, analyzers, and some frameworks. Generic annotations, attributes such as NotNullWhen, and collection element nullability communicate contracts. External systems can still violate them through deserialization, reflection, interop, database values, or unannotated assemblies.
Migration and design
Enable nullable analysis incrementally for legacy projects, resolve warnings at boundaries, and avoid mass null-forgiving operators. Model absence distinctly from empty values and validation failures. Keep annotations accurate across overrides and generic APIs. Do not treat warnings as proof that null cannot occur at runtime.
Interview questions
- Are
stringandstring?different CLR types? No; nullability is compile-time annotation metadata. - What does
!do? Suppresses nullable analysis at that expression; it adds no runtime check. - Does nullable enable guarantee no NRE? No; runtime inputs and legacy/interop code can violate annotations.
- What does the compiler track? Null state through control-flow analysis.
- How migrate a large codebase? Enable incrementally, fix boundaries/contracts, and avoid blanket suppression.