Avoid CS8618 warning when initializing mutable non nullable property with argument validation

For now you can avoid this warning by initializing a _name field using default value with null-forgiving operator !, like

private string _name = default!;

or

private string _name = null!;

There is also an open GitHub issue for that.

You can also declare the _name as string? and specify that return value of Name property can't be null (even if string? type allows it), using NotNull attribute

private string? _name;

[NotNull]
public string? Name
{
    get => _name;
    set => _name = value ?? throw new ArgumentNullException("Name is required.");
}

It should be fine, otherwise compiler shows you a warning before validation logic will take place in a setter

set => _name = value ?? throw new ArgumentNullException("Name is required.");

Consider the following code

var person = new Person(null);

In this case you'll get

warning CS8625: Cannot convert null literal to non-nullable reference type.

before ArgumentNullException will be thrown.

If you set <TreatWarningsAsErrors>true</TreatWarningsAsErrors> or treat CS8625 warning as error, your exception won't be thrown


Based on this:

Warnings for initialized fields Q: Why are warnings reported for fields that are initialized indirectly by the constructor, or outside the constructor?

A: The compiler recognizes fields assigned explicitly in the current constructor only, and warns for other fields declared as non-nullable. That ignores other ways fields may be initialized such as factory methods, helper methods, property setters, and object initializers. We will investigate recognizing common initialization patterns to avoid unnecessary warnings.

So with that being said, for now, moving the assignment directly into the constructor, is the only possible way. And for sure, using the pragma directive seems fine for this IMO.


You can disable the rule by creating an .editorconfi file (with the attached code) in the root of your project. It does not solve it but it will no longer show the warning

[*.cs]

# CS8618: Non nullable field _name is not initialized. Consider declare the field as nullable type
dotnet_diagnostic.CS8618.severity = none