Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

CS8618: Non-nullable property must contain a non-null value

Nullable reference types caught a promise the constructor does not keep. Choose required, a constructor parameter, an honest string? or a documented null-forgiving default.

~5 min readC#
#C##.NET#Nullable Reference Types#Compiler Warnings
3D diagram of a class box with an empty property slot glowing red and an amber key approaching, headline CS8618

Introduction & Quick Summary

Symptom. Every entity and DTO in the project reports:

code
warning CS8618: Non-nullable property 'Name' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Cause. <Nullable>enable</Nullable> turns on nullable reference types. A property declared public string Name { get; set; } promises that it is never null, but the compiler can see no assignment on every path out of the constructor, so it reports the broken promise. The warning is accurate: new User().Name is null at runtime, and any code that trusts the annotation crashes later with NullReferenceException far from this class.

Fix. Say which of three things is true. The value is mandatory from the caller: use required (C# 11) or a constructor parameter. The value is genuinely optional: declare it string?. The value is supplied by a framework after construction (EF Core, a serializer, DI): assign null! once, with a comment, or annotate the helper that sets it with [MemberNotNull].

Core Mechanics, Signatures & Reproducible Setup

Nullable reference types are annotations the compiler checks in your code; they are not runtime guards. CS8618 is a definite assignment analysis over constructors: if a non-nullable member is not assigned before every return, the constructor is flagged.

A reproduction in a console project:

xml
<!-- the two lines that make this compile-time visible --> <PropertyGroup> <Nullable>enable</Nullable> <LangVersion>latest</LangVersion> </PropertyGroup>
csharp
public sealed class User { public string Name { get; set; } // CS8618 public string? Nickname { get; set; } // fine: explicitly optional public required string Email { get; set; }// fine: caller must set it public User() { } // Name never assigned }

The four settings of the <Nullable> property decide how much you see:

xml
<Nullable>disable</Nullable> <!-- no warnings, no annotations, no help --> <Nullable>annotations</Nullable> <!-- annotations allowed, warnings off: libraries --> <Nullable>warnings</Nullable> <!-- warnings on, annotations off: migration --> <Nullable>enable</Nullable> <!-- both: what you want in application code -->

Key Comparison Table

Five ways to satisfy the compiler, with what each one promises the caller:

DeclarationCaller must set itCompiler sees a valueRight for
public required string Name { get; init; }Yes, at object creationYesDTOs, options, records (C# 11 / .NET 7+)
Constructor parameter assigned in ctorYes, via new(...)YesImmutable domain models
public string Name { get; set; } = "";NoYesCollections, strings with a meaningful empty
public string? Name { get; set; }NoNo, honestlyTruly optional data
public string Name { get; set; } = null!;NoTrusts youFramework-populated entities

The nullable warnings you meet after CS8618:

WarningMessageFix
CS8618Non-nullable property must contain a non-null valueThis article
CS8625Cannot convert null literal to non-nullable reference typeDo not pass null; change the parameter to T?
CS8602Dereference of a possibly null referenceGuard, ?., or ! after a real check
CS8603Possible null reference returnReturn T? or throw
CS8604Possible null reference argumentNarrow before the call
CS8629Nullable value type may be null.Value after a check, or ??

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. required and object initializers

required moves the check to every construction site, which is what CS8618 asks for:

csharp
public sealed class CreateUserRequest { public required string Name { get; init; } public required string Email { get; init; } public string? Referrer { get; init; } } var request = new CreateUserRequest { Name = "Ada" }; // CS9035: required member 'Email' var ok = new CreateUserRequest { Name = "Ada", Email = "ada@example.com" };

The error code for a missing required member is CS9035, and it appears where the object is created rather than inside the class — a much better place to read it. required needs C# 11 and .NET 7 or later; on .NET 6 the same intent is a constructor parameter.

2. Constructor parameters for immutable models

Where required is unavailable, or the type should be immutable, assign in the constructor and keep the property get-only:

csharp
public sealed class Money { public decimal Amount { get; } public string Currency { get; } public Money(decimal amount, string currency) { Amount = amount; Currency = currency ?? throw new ArgumentNullException(nameof(currency)); } }

The ?? throw is redundant once the parameter is non-nullable string, and essential at the boundary where the parameter is string?. Choosing string? on the parameter and throwing inside the constructor is the pattern that documents the requirement in the signature and enforces it at runtime.

3. Helper methods: [MemberNotNull]

A constructor that delegates initialization to a private method cannot be analysed, so CS8618 comes back even though every path assigns:

csharp
using System.Diagnostics.CodeAnalysis; public sealed class Connection { public string Host { get; private set; } public Connection(string host) => Initialize(host); [MemberNotNull(nameof(Host))] private void Initialize(string host) { Host = host; } }

[MemberNotNull] tells the compiler what the method guarantees, and it is checked: if Initialize stops assigning Host, the attribute itself produces a warning (CS8774). [NotNull], [MaybeNull] and [AllowNull] cover the parameter and return positions.

4. Entities populated by a framework

EF Core materialises entities through reflection and sets properties after the constructor runs. That is exactly the case the annotation cannot express, and null! is the accepted idiom:

csharp
public sealed class Order { public int Id { get; set; } public string Reference { get; set; } = null!; // set by EF Core public List<OrderLine> Lines { get; set; } = new(); }

Two rules keep this honest: a comment naming the framework, and no constructor of your own that could observe the null. required on an EF entity forces new Order { Reference = ... } at every construction site, including test builders; most teams pick null! for entities and required for DTOs.

5. Deserialization and options binding

A type with required members is fine for System.Text.Json on .NET 8 and later and for Microsoft.Extensions.Configuration binding, but a type whose non-nullable properties have no defaults will bind to nulls silently at runtime when the JSON key is missing — the compiler cannot see inside the serializer:

csharp
public sealed class SmtpOptions { public string Host { get; init; } = ""; public int Port { get; init; } = 587; public string User { get; init; } = ""; public void Validate() { if (string.IsNullOrWhiteSpace(Host)) throw new InvalidOperationException("Smtp:Host is not configured"); } }

Initialising to "" satisfies the compiler and leaves a value that a Validate() call can catch at startup. That is better than null! for configuration, because a missing key produces a clear startup error instead of a null reaching the SMTP client.

6. Making nullable warnings fail the build

In an existing solution, thousands of CS8618 warnings are ignored until they are errors. Turn them on per project, after the bulk of the code is fixed, using the nullable warning ID range:

xml
<!-- Directory.Build.props --> <PropertyGroup> <Nullable>enable</Nullable> <WarningsAsErrors>nullable</WarningsAsErrors> </PropertyGroup>

nullable as a WarningsAsErrors category catches CS86xx warnings without making unrelated warnings fatal. For generated code, silence narrowly with #nullable disable at the top of the file and #nullable restore after it, rather than <NoWarn>, which also hides the warning in files you own.

Common Compilation/Runtime Mistakes & Version Gotchas

  • = null! on everything. It compiles, removes the pressure to decide, and the null still reaches production; every use needs a reason in a comment.
  • Declaring the property string? to silence the warning. This is correct only if the data is optional; making half the model nullable pushes CS8602 into every consumer instead.
  • required on a type your framework instantiates with new(). Generic code with where T : new() and DI containers that call the parameterless constructor now fail to compile or throw; required propagates.
  • Forgetting SetsRequiredMembers. A constructor that assigns required members still leaves callers forced to use initializers unless it is annotated with [SetsRequiredMembers].
  • Nullable context inherited from a package. A library compiled with <Nullable>disable</Nullable> exposes oblivious types to your enabled project, and the warnings appear in your code; the fix belongs in the library, or in a local #nullable enable around your wrappers.
  • LangVersion without the targeting pack. required needs C# 11 and a runtime with the compiler support; setting LangVersion=preview on an old SDK produces confusing errors instead of the feature.
  • Warnings-as-errors in CI only. The build passes locally and fails on the pipeline because TreatWarningsAsErrors lives in the CI script; put it in Directory.Build.props so both see the same rules.
  • Records with positional parameters. public record User(string Name) never triggers CS8618, which makes records look like a free fix; the requirement has simply moved into the constructor.

Related tools. When the null arrives from an HTTP payload, format the body with the JSON formatter to see whether the key was missing, null, or an empty string — the three bind to different values and only one of them is caught by Validate() — and diff the request and response with the text diff tool when a nullable property starts coming back as null after a schema change.

Official references

primary documentation

The C# documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.