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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)