skip to content

Nullable Reference Types

With nullable reference types on, string means non-null and string? may be null, but the checks are compile-time warnings only. Interviewers ask how to migrate a codebase.

on this pageshow

explore

questions

6

With nullable reference types enabled in C#, what does writing string? instead of string change at compile time and at run time?

level: juniorimportance: must knowfreq 75%

answer

  1. compile time versus run time
  2. one CLR type underneath
  3. CS8600, CS8602, CS8603
  4. warnings, no inserted checks

basics

~20 s

Only the compiler's analysis changes. string? says the value may be null, so unchecked dereferences warn; string promises non-null, so a possible null flowing in warns. Both are System.String at run time, with no inserted null checks.

solid answer

~40 s

In a nullable-enabled context the `?` on a reference type is an **annotation**, not a new type: `string` and `string?` both compile to `System.String`, and the compiler records the intent as metadata attributes. That intent feeds null-state analysis: assigning a maybe-null value to a `string` local warns CS8600, passing a `null` literal to a `string` parameter warns CS8625, dereferencing an unchecked `string?` warns CS8602, returning maybe-null from a `string` method warns CS8603, and a constructor that leaves a non-nullable field unset warns CS8618. They are warnings, so the build succeeds, and no run-time check is added: a null that slips past still throws `NullReferenceException` where it is dereferenced. That is the difference from `int?`, which really is another type, `Nullable<int>`.

code

csharp · 8 lines
csharp
string? nickname = args.Length > 0 ? args[0] : null;
string display = nickname;          // warning CS8600, still compiles
Console.WriteLine(display is null); // True: no run-time check was added

Greet(null);                        // warning CS8625
Console.WriteLine(nickname.Length); // warning CS8602

static void Greet(string who) => Console.WriteLine($"Hi, {who}!");

go deeper

for a junior

Recall that the question mark on a reference type is an annotation the compiler checks, that both forms are System.String, and name CS8600 and CS8602.

for a middle

Explain null-state: non-nullable starts not-null, nullable starts maybe-null, and each warning marks a disagreement between intent and flow; contrast it with int? being Nullable<int>.

for a senior

Show you know where the guarantee ends: no inserted checks, so callers with nullable off, deserializers and arrays still deliver null to non-nullable members.

for a principal

Frame annotations as part of a published contract: they ship as metadata, changing them is a source-level warning change rather than a binary break, and public APIs still need run-time guards.

## An annotation, not a new type C# 8 added **nullable reference types**, and every supported C# version has them. When the nullable context is enabled (the `<Nullable>enable</Nullable>` project property, which current project templates write, or a `#nullable enable` directive), every reference type you write without a suffix is **non-nullable** and every type with `?` is **nullable**. The suffix is an **annotation**: a statement of intent that the compiler checks, not a different CLR type. - `string` and `string?` are both `System.String`. `((string?)"a").GetType()` prints `System.String`. - You cannot overload on the annotation: declaring `M(string s)` and `M(string? s)` in one class is error CS0111, because both have the same parameter types. - `Nullable<string>` does not exist: `Nullable<T>` requires a non-nullable value type, and the compiler reports CS0453. - The annotations travel to other assemblies as metadata attributes: the compiler records the prevailing annotation of a method or type with `System.Runtime.CompilerServices.NullableContextAttribute` and marks the exceptions with `NullableAttribute`. A consumer compiled with nullable enabled reads them and warns accordingly. ## What the compiler checks The compiler tracks a **null-state** for every expression: *not-null* or *maybe-null*. A non-nullable variable starts not-null and a nullable one starts maybe-null. The warnings fire where the declared intent and the tracked state disagree: | Code | Message (SDK 10.0.401) | Typical trigger | |---|---|---| | CS8600 | Converting null literal or possible null value to non-nullable type. | `string name = nickname;` where `nickname` is maybe-null | | CS8625 | Cannot convert null literal to non-nullable reference type. | `Greet(null)` for a `string` parameter | | CS8602 | Dereference of a possibly null reference. | `nickname.Length` with no check | | CS8603 | Possible null reference return. | `return null;` from a method returning `string` | | CS8618 | Non-nullable field 'Email' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the field as nullable. | a constructor that never sets a non-nullable field | Each fix states the intent more truthfully: add a null check, change the declaration to `string?`, initialize the member, mark it `required`, or annotate the API that produced the value. ## What does not change at run time This is the half of the answer weak candidates miss. Nullable reference types are a compile-time feature only: 1. Method bodies compile to the same IL; only metadata attributes record the annotations. No `if (x == null) throw` is inserted into a method with a non-nullable parameter. 2. A warning does not stop the build unless the project turns warnings into errors. 3. A non-nullable `string` can still hold null at run time: an ignored warning, a caller compiled with nullable disabled, a deserializer, a new array of strings, or a `!` suppression all put it there without any check. 4. When that null is dereferenced you get the same `NullReferenceException` as before the feature existed. ```csharp string? nickname = args.Length > 0 ? args[0] : null; string display = nickname; // CS8600, but it compiles Console.WriteLine(display is null); // True: nothing checked the assignment ``` So the annotation is a contract that the compiler helps you keep inside code it compiles with the context enabled. Outside that boundary, the value is whatever the caller sent. ## How it differs from nullable value types `int?` is a different story: it is `Nullable<int>`, a struct with `HasValue` and `Value`, and `int` and `int?` really are different run-time types. That belongs to the lesson on nullable value types; here it matters only as the contrast. For a reference type, `?` changes nothing in the type system the runtime sees, and the same syntax means two very different things depending on whether the type underneath is a class or a struct. ## Reading the warnings in practice - Treat a CS8602 on a `string?` as "this path has no null check", not as noise: either add the check or ask why the declaration says null is possible. - Treat a CS8600 or CS8604 as a mismatch between two declarations: one side says null is possible, the other says it is not, and one of them is wrong. - Treat CS8618 as a construction problem: the object can exist in a state its own type says is impossible. - When nullable is enabled, `var` declares the nullable form of the inferred type; its null-state still comes from the initializer, so `var name = "Ada";` starts not-null and accepts a later `name = null;` without a warning. The short version an interviewer wants: `string?` versus `string` changes the warnings you get and the contract you publish, and nothing about what the runtime does with a null.

  • If string and string? are the same CLR type, how does a consuming assembly know which one your method returns?
    The compiler writes the annotations into metadata as attributes: `NullableContextAttribute` on a method or type whose annotations agree, and `NullableAttribute` where individual types differ. A consumer compiled with nullable enabled reads them and warns accordingly. The IL signature still says `System.String`, so changing an annotation is not a binary break; it only changes the warnings recompiled callers see.
  • Can a C# class overload a method on string versus string??
    No. Both parameters are `System.String`, so `void M(string s)` and `void M(string? s)` have the same parameter types, and the compiler rejects the second declaration with error CS0111 (the type already defines a member with the same parameter types). Nullability is never part of a signature for overloading.
  • What happens if you write string? in a project where nullable is disabled?
    The code still compiles, but the compiler warns CS8632: "The annotation for nullable reference types should only be used in code within a '#nullable' annotations context." The `?` has no meaning there, because every reference type is already nullable-oblivious.

A 'fragile' sticker on a parcel: everyone who reads it handles the box differently, but the sticker does not change what is inside, and nothing at the destination enforces it.

  • string? is a separate type, like Nullable<string>.
  • Enabling nullable makes the runtime reject null for string parameters.
  • A nullable warning stops the build by default.
  • A non-nullable string field can never hold null at run time.
  • You can overload a method on string and string?.
open as a page

In C#, what does the null-forgiving operator ! do at compile time and at run time, and when does using it become a problem?

level: middleimportance: must knowfreq 60%

basics

~20 s

Postfix ! tells the compiler an expression is not null, suppressing nullable warnings for that expression. It emits no code and no check: x! evaluates to x, so a wrong ! simply moves the NullReferenceException to a later line.

open as a page

In a C# project, what do the Nullable property values enable, warnings, annotations and disable each turn on, and how do #nullable directives override them?

level: middleimportance: should knowfreq 55%

basics

~20 s

The nullable context has two flags: annotations (whether ? and non-nullable types mean anything) and warnings (whether null-state warnings are reported). enable sets both, disable neither, warnings and annotations one each; #nullable directives change either flag for the rest of a file.

open as a page

With nullable reference types enabled, how does C# flow analysis decide whether a dereference earns warning CS8602, and where can it be fooled?

level: middleimportance: should knowfreq 45%

basics

~20 s

The compiler tracks each expression as not-null or maybe-null: declarations set the start, assignments and null checks change it, and CS8602 fires on dereferencing a maybe-null value. It reads only signatures, so helpers and method calls that change fields go unseen.

open as a page

A C# service built with <Nullable>enable</Nullable> and no nullable warnings throws NullReferenceException on a non-nullable string property; how can null get there?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Non-nullable is a compile-time promise with no run-time check. Null still arrives from code the analysis never sees: deserializers and reflection, new arrays and default structs, callers or libraries compiled with nullable disabled, and ! or null! suppressions.

open as a page

A ten-year-old C# customer-support backend turns on <Nullable>enable</Nullable> and gets two thousand warnings; how would you plan the migration and decide when nullable warnings become errors?

level: principalimportance: should knowfreq 40%

basics

~20 s

Turn the warnings into a sequenced backlog: pick a project default and #nullable directives, migrate bottom-up from leaf types, fix the APIs that really return null, and make nullable warnings errors once migrated code is clean, so the backlog can only shrink.

open as a page