Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Types and Literals

C# nullable reference types

Reference for C# nullable reference types: the #nullable context, string? versus string, flow analysis, the ! operator, attributes and common warnings.

Nullable reference types (NRT) are a compile-time feature that helps you find NullReferenceException bugs before they run. When the feature is enabled, a reference type written without a question mark, like string, is promised to be non-null, and string? explicitly allows null. The compiler tracks which variables might be null at each point and warns when you dereference one that could be.

Nothing changes at run time: string? and string are the same type, and null is still a legal value for any reference. The checks are warnings (CS8600 to CS8625), which you can promote to errors. Our runner compiles with nullable enabled, so the examples below behave like a new .NET 10 project.

C#
#nullable enable
string name = "Ada";      // never null
string? nickname = null;  // may be null

Try it

C# Flow analysis in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# A warning, the ! operator and attributes (warns on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
#nullable enable      // turn the annotations and warnings on for the rest of the file
#nullable disable     // oblivious: no warnings
#nullable restore     // back to the project setting

string  a;            // non-nullable
string? b;            // nullable
b!                    // null-forgiving operator

Project setting in the .csproj file: <Nullable>enable</Nullable>. The default for new .NET projects is enabled.

Attribute (System.Diagnostics.CodeAnalysis) Meaning
[NotNull], [MaybeNull] The returned or ref value is (or is not) never null, regardless of the declared type.
[NotNullWhen(bool)], [MaybeNullWhen(bool)] For out parameters, depending on the return value.
[NotNullIfNotNull("p")] Return is non-null when parameter p is non-null.
[MemberNotNull(...)] After the method runs, listed fields are non-null.
[DisallowNull], [AllowNull] Input restrictions for properties and parameters.
[DoesNotReturn] The method always throws or exits.

Errors / undefined behavior. Violations are compiler warnings, not errors. At run time, dereferencing a null still throws NullReferenceException.

Usage notes

  • Initialize non-nullable fields. Fields and properties of non-nullable reference types must be assigned in every constructor, or be marked required, or the compiler warns (CS8618).
  • ! does not check anything. It only silences a warning. Use it sparingly, for example after a framework call whose annotations are wrong.
  • Generics. An unconstrained T may be null or not; use T? with where T : class or where T : struct, or [MaybeNull].
  • default! for fields filled later by frameworks (dependency injection, serializers) is common but hides real problems; prefer required members.
  • Arrays. string[] means the array and its elements are non-null, but new string[3] fills it with null and produces no warning at the creation point.
  • Library annotations. The .NET libraries are annotated, so Dictionary<K,V>.TryGetValue and string.IsNullOrEmpty carry the right attributes.
  • Migration. Enable the feature per file with #nullable enable and fix warnings gradually; they never change behavior.
  • Not a guarantee. Reflection, unsafe code and callers with the feature disabled can still pass null to a string parameter. Validate public APIs with ArgumentNullException.ThrowIfNull(x).