Glossary / Nullability annotations

Nullability annotations

Nullability annotations are the ? markers and metadata that describe whether reference values may be null, along with attributes that refine compiler flow analysis. They form a communication contract among library authors, callers, analyzers, serializers, and frameworks, while the runtime representation remains an ordinary reference.

Annotations and metadata

In an enabled context, string is annotated non-nullable and string? nullable. Nullable value types use a different runtime construct, Nullable<T>. Compiler-emitted nullable metadata lets downstream compilers inspect declarations; attributes such as [MaybeNull], [NotNull], [NotNullWhen], and [MemberNotNull] describe contracts the type syntax alone cannot express. The compiler trusts these annotations and attributes, so inaccurate declarations can create unsound warnings or false confidence.

Oblivious code compiled without nullable context may flow into annotated APIs with reduced guarantees. Public libraries should preserve annotations in packages and consider compatibility when changing nullability: making an output nullable or an input more restrictive can break callers or introduce warnings. Reflection and serialization libraries may interpret metadata as runtime schema hints, but this is library behavior rather than CLR enforcement.

Engineering guidance

Annotate public APIs accurately, use attributes for conditional postconditions, and test null behavior at runtime boundaries. Review overrides and interface implementations for contract consistency. Treat nullable warnings as design feedback, not merely noise to silence with !.

Interview questions

  1. Do annotations change object layout? No; reference nullability is compiler metadata/analysis.
  2. When use NotNullWhen? To express that a parameter is non-null when a method returns a specified boolean value.
  3. Can legacy code preserve guarantees? Not fully; oblivious annotations weaken flow analysis.
  4. Can nullability changes affect API compatibility? Yes, source consumers may gain warnings/errors and tools may interpret metadata.
  5. Are annotations runtime validation? No, though frameworks may use metadata as input to their own behavior.

References