I have a question regarding nullable reference type system available since C# 8.
Suppose we have a C# domain model class with a mutable reference type property like below:
public class Person
{
public string Name { get; set; }
public Person(string name)
{
Name = name;
}
}
So far no problem. But consider real world scenario, I often want to check the validity of the property as it's a public mutable property and I have to make sure the model invariant whenever property is changed.
public class Person
{
private string _name;
public string Name
{
get => _name;
set => _name =
value ?? throw new ArgumentNullException("Name is required.");
}
public Person(string name)
{
Name = name;
}
}
Then compiler generates CS8618 warning, basically saying:
Non nullable field _name is not initialized. Consider declare the field as nullable type.
So every time I encounter the warning I have to enclose the constructor with the following pragma directive.
#pragma warning disable CS8618
public Person(string name)
{
Name = name;
}
#pragma warning restore CS8618
But I think it's redundant and tedious to do it always. Am I misusing something or is there better way to write such property without warning?
Of course I can change the property type to string? as compiler suggests but notionally it's not acceptable as a solution as Person should always have non null name and we want to explicit about such invariant condition in domain class.
Another solution I considered is to drop the argument validation logic and just relying on the nullable compiler warning, but it's not always possible (I mean often validation other than null check is also required.), it's just warning anyway in regular project settings, so I don't think it's a good solution.
string?ornull!you could userequiredmodifier likepublic required string Name {get;set;}to suppress that warning.