'What is best way to create .NET6 class with many non-nullable properties?
I trying to create class with some number of non-nulable properties (>7).
If I do like this:
public class Meeting
{
public Name Name { get; set; }
public Person ResponsiblePerson { get; set; }
public Description Description {get; set; }
public Category Category { get; set; }
public Type Type { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public List<Person> Attendees { get; set; }
public Meeting()
{
Attendees = new List<Person>();
}
}
I get warnings like this: "Non-nullable property '...' must contain a non-null value when exiting constructor. Consider declaring the property as nullable."
There is a list of variants I thinked of:
Default values removes this warning, but I think, that it will just add useless values, that in the future will be needed to be changed anyway.
If I init all properties in constructor this warning gets away, but then constructor will have >7 params which is nightmare.
I have seen that some people use "Builder" pattern to init classes with many params. But the builder itself can't prevent 'null' values (The builder will get same warnings).
There is easy way to remove warning, by making nullable property in .csproj file from true to false, but I don't want to just remove that warning. I want to make class itself safe from null values.
Whats clean way create that class?
Solution 1:[1]
The whole point of non-nullable is to initialize class instances in a "valid" state.
If Meeting is part of a domain, having some logic inside, you can't initialize Meeting without initial values. I.e., new Meeting() doesn't make any sense.
On the other hand, if Meeting is a so-called data transfer object and it may be initialized partially, if not even empty, then setters are fine, and you don't need a constructor.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Karlis Fersters |
