Skip to content

/errors/csharp/cs8618-non-nullable-property-must-contain-non-null-value

C# warning CS8618: Non-nullable property must contain a non-null value when exiting constructor

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · 10.0.401updated
tool
C#
exit code
0
versions
C# 8+ with nullable reference types, .NET 6 – 10 (enabled by default in new projects)
os
any

warning CS8618: Non-nullable property 'Name' must contain a non-null value when exiting constructor comes from C# nullable reference types. The property is declared as string (meaning "never null"), but after the constructor finishes nothing has assigned it, so it is still null. Mark it required, give it an initial value, set it in the constructor, or declare it string? if null is allowed.

Reproduce it

bash
dotnet new console -o app >/dev/null 2>&1
cd app
cat > Program.cs <<'EOF'
var u = new User { Name = "Ada" };
Console.WriteLine(u.Name);

class User
{
    public string Name { get; set; }
}
EOF
dotnet build -nologo 2>&1 | grep -o 'warning CS8618: [^[]*' | sort -u

Output

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.

The build succeeds: CS8618 is a warning. Projects with <TreatWarningsAsErrors>true</TreatWarningsAsErrors> (or <WarningsAsErrors>nullable</WarningsAsErrors>) turn it into error CS8618 and the build fails.

Fix: required, initializer, constructor or nullable

bash
dotnet new console -o app >/dev/null 2>&1
cd app
cat > Program.cs <<'EOF'
var u = new User { Name = "Ada" };
var o = new Order("A-1");
Console.WriteLine($"{u.Name} {u.Email.Length} {o.Id} {u.Nickname ?? "(none)"}");

class User
{
    public required string Name { get; set; }       // callers must set it
    public string Email { get; set; } = string.Empty; // default value
    public string? Nickname { get; set; }           // null is allowed
}

class Order(string id)                               // primary constructor (C# 12)
{
    public string Id { get; } = id;
}
EOF
dotnet build -nologo 2>&1 | grep -c 'CS8618'
dotnet run --no-build

Output

0
Ada 0 A-1 (none)
FixUse when
required string NameThe caller must always provide the value (C# 11+)
string Name = string.EmptyAn empty value is a sensible default
Assign in the constructorThe value is a constructor argument
string? NameThe value is genuinely optional
string Name = null!A framework sets it later; silences the warning without any check

Sources