C# Nullable Reference Types and #nullable enable Explained
How C# nullable reference types work, what #nullable enable does under the hood, how to resolve CS8618 without null!, and how to teach the compiler with attributes.
Quick answer
Nullable reference types in C# use compile-time static flow analysis to warn you about potential NullReferenceExceptions. Enabling them via <Nullable>enable</Nullable> in your .csproj or #nullable enable in a file treats reference types as non-nullable by default, requiring a ? suffix (like string?) when null is permitted. This is a compiler check only: at runtime, string and string? are identical CLR types.
Tony Hoare called null references his “billion-dollar mistake”. For two decades in C#, every reference type you touched (string, Customer, Stream) could secretly be null, and you found out at runtime (Boom!). Nullable reference types are C#’s attempt to fix that without breaking twenty years of existing codebases and production environments.
With nullable reference types enabled, reference types are non-nullable by default. You write string? when you want to allow null, and the compiler warns you when you dereference something that could be null. It is a compile-time check and a developer experience improvement. At runtime, string and string? are the same type, so the compiler cannot stop null from sneaking in.
Most of the confusion comes from a misunderstanding of what the compiler promises and what the runtime does. Let’s walk through it.
The compiler illusion versus the CLR
Nullable value types and nullable reference types look alike but work very differently.
int? is syntactic sugar for System.Nullable<int>, a real struct with HasValue and Value. It exists at runtime. The CLR knows an int? is different from an int.
string? is just System.String. There is no wrapper, no extra type, no runtime difference. The proof is that you can’t even ask for the nullable version. typeof(string?) is a compile error (CS8639), because there’s no distinct type to hand back:
// CS8639: the typeof operator cannot be used on a nullable reference typevar t = typeof(string?);
// This is the whole story at runtimeConsole.WriteLine(typeof(string).FullName); // System.StringSo how does the compiler track nullability at all? Two separate mechanisms. Inside a method, it runs flow analysis at build time to decide whether a given expression might be null, and that drives the warnings in your favorite editors and build tools. For the public surface (parameters, return types, fields, properties), it records the declared annotations in metadata as [Nullable(byte)] and [NullableContext(byte)] attributes, so other assemblies can see your nullability intent. Those attributes do live in the compiled assembly, and you can read them back with reflection; the CLR simply never enforces them. Flow analysis leaves no runtime trace.
A third-party package compiled without annotations, a reflection call, or a JSON deserializer can all drop a null into a variable you declared non-nullable. The compiler stays quiet because, as far as it knew at build time, everything checked out.
Turning it on: <Nullable>enable</Nullable> versus #nullable enable
Set it project-wide in your .csproj or, better, in a Directory.Build.props at the repository root so every project inherits it:
<PropertyGroup> <Nullable>enable</Nullable></PropertyGroup>For a legacy project, flipping that switch can produce thousands of warnings at once. Use the file-scoped directive to migrate one file at a time instead:
#nullable enableThe context has four states:
enable: annotations (?) and warnings both on. This is the goal.disable: pre-C# 8 behavior, nullable-oblivious.warnings: warnings on, annotations off.annotations: annotations on, warnings off.
#nullable restore resets a file back to whatever the project setting is, which is handy at the bottom of a block you temporarily changed.
Fixing the three warnings you’ll actually hit
Most nullable noise comes down to a handful of compiler codes. Use this table as a quick lookup before diving into the patterns below.
| Warning | Meaning | Typical fix |
|---|---|---|
CS8602 |
Dereference of a possibly null reference | Guard with is not null, ?., or ?? |
CS8618 |
Non-nullable field or property is uninitialized | Add required, initialize in a constructor, or set a default |
CS8603 |
Possible null reference return | Change the return type to T? or handle the null path |
CS8604 |
Possible null reference argument | Guard before calling or make the parameter T? |
CS8625 |
Cannot convert null literal to non-nullable type |
Change the variable or parameter default to T? |
CS8632 |
? annotation used outside #nullable context |
Enable #nullable enable or <Nullable>enable</Nullable> |
CS8602: dereference of a possibly null reference
You call a member on something that might be null:
string? middleName = GetMiddleName();int length = middleName.Length; // CS8602Pick whichever fix matches your intent:
// Skip it if nullint? length = middleName?.Length;
// Fall back to a defaultint fallbackLength = (middleName ?? string.Empty).Length;
// Guard, and the compiler tracks the narrowingif (middleName is not null){ Console.WriteLine(middleName.Length); // no warning}CS8618: non-nullable member uninitialized
This warning commonly appears in codebases heavily dependent on DTOs, entities, and options classes:
public class Customer{ public string Name { get; set; } // CS8618}The straightforward fix is public string Name { get; set; } = null!;, but please don’t do that if you can avoid it. That tells the compiler to stop warning while leaving the property genuinely null, which defeats the whole point. You have three real options:
// Option 1 — C# 11 required: callers must set it in an initializerpublic class Customer{ public required string Name { get; set; }}
// Option 2 — primary constructor: set it from a constructor argumentpublic class Customer(string name){ public string Name { get; set; } = name;}
// Option 3 — a sensible defaultpublic class Customer{ public string Name { get; set; } = string.Empty;}required is usually the right call for models. The compiler forces callers to write new Customer { Name = "Khalid" } and won’t let them forget.
CS8603 and CS8604: possible null return or argument
CS8603 fires when you return null from a method declared non-nullable. CS8604 fires when you pass a string? into a parameter that wants string. Both mean your signature is lying about intent. If a method can fail to find a result, say so and return string?. Then callers have to handle the null, which is the behavior you wanted anyway.
The null-forgiving operator (!): use it rarely, and say why
The ! operator, the “bang” or “dammit” operator (shut your mouth), tells the compiler “trust me, this isn’t null.” It emits no runtime code. It only strips the warning. If you’re wrong, you still get a NullReferenceException, except now the compiler won’t warn you next time either.
There are legitimate uses:
- EF Core entity properties the framework populates by reflection.
- Test fields initialized in a
[SetUp]or constructor before any test runs. - Interop with an unannotated package where you have real runtime certainty.
If you reach for ! to silence a warning, and you can’t explain the framework guarantee behind it, you’re hiding a bug, not fixing one.
Teaching the compiler with attributes
Flow analysis stops at method boundaries. The compiler can’t see that your helper method guarantees something, so you tell it with attributes from System.Diagnostics.CodeAnalysis.
[NotNullWhen(true)] is the one you’ll use most, for Try* methods:
using System.Diagnostics.CodeAnalysis;using Microsoft.Extensions.Configuration;
public static class ConfigExtensions{ public static bool TryGetConfig( this IConfiguration config, string key, [NotNullWhen(true)] out string? value) { value = config[key]; return value is not null; }}Now when a caller writes if (config.TryGetConfig("x", out var value)), the compiler knows value is non-null inside the if.
[MemberNotNull(nameof(field))] marks a helper that initializes fields, so the compiler stops complaining that your constructor left them null. [MemberNotNullWhen(true, nameof(Property))] handles the guarded-property case. I covered that one in detail in Fix CS8602 and Nullability Warnings for Guarded Members.
Where null still sneaks in
The compiler misses a few cases entirely. Know them.
Default structs. A struct with a non-nullable reference field gives you no warning when you default it:
UserProfile profile = default; // compiles, no warningConsole.WriteLine(profile.DisplayName.Length); // NullReferenceException
public struct UserProfile{ public string DisplayName;}Arrays of reference types. new string[10] gives you ten null slots, but the element type is string, not string?, so the compiler says nothing.
JSON deserialization. Give a class a plain non-nullable property with no required and no initializer, and a missing value comes back null:
using System.Text.Json;
// Name is null, even though the type says non-nullablevar customer = JsonSerializer.Deserialize<Customer>("{}");
public class Customer{ public string Name { get; set; } // CS8618 at compile time}Marking Name as required makes the missing value throw during deserialization instead. Turning on RespectNullableAnnotations is not enough on its own: it makes an explicit null for a non-nullable property throw, but an absent property is never set, so it stays null without complaint. For the "{}" case, where the property is simply missing, required is what catches it. This is the one that bites in production, because the bad data comes from outside your build.
FAQ
Does #nullable enable prevent NullReferenceException at runtime?
No. It’s compile-time static analysis. Reflection, external input, and unannotated libraries can still hand you a null.
What’s the difference between Nullable<T> and nullable reference types?
Nullable<T> (int?) is a real CLR struct. Nullable reference types (string?) are compiler metadata only. At runtime, string and string? are both System.String.
What does ! mean after a variable or property?
It’s the null-forgiving operator. It suppresses null warnings on that expression and asserts you guarantee the value isn’t null. It changes nothing at runtime.
How do I enable nullable reference types across a whole solution?
Add <Nullable>enable</Nullable> to a Directory.Build.props file in your repository root.
Null handling is one section of the larger C# cheat sheet if you want the quick-reference version alongside the rest of the everyday syntax.
Around the web
Comments
Loading comments from GitHub Discussions…