If we declare property like this:
public class Cat
{
public string Name { get; set; }
}
we get a warning compilation:
CS8618 - Non-nullable variable must contain a non-null value when exiting constructor. Consider declaring it as nullable.
because Name property is not initialized.
Imagine, this is mandatory property (business rules say it). We can try to solve it by several ways:
- Constructor declaration:
a) In ctor directly:
public class Cat
{
public Cat()
{
Name = string.Empty;
}
public string Name { get; set; }
}
b) in property:
public class Cat
{
public string Name { get; set; } = string.Empty;
}
really, both options is the same (syntax sugar).
pros: we can use init of class like Cat cat = new ();
cons: property is initialized by 'dummy' value when object is created and will be rewritten. Or (much more major) will not be rewritten by some unknown reasons (e.g. we use automapper and source object had empty value for this field or we forgot to map this field) and in result object will have invalid value (by business rules property can't be empty, cat must have a name)
- declare field as nullable:
public class Cat
{
public string? Name { get; set; }
}
for me, it's invalid approach (although it's described here as alternative), our business rule says, that Name is mandatory and model can't be valid without this property (so, in the best conditions, it should not be even created)
- Use
requiredkeyword:
public class Cat
{
public required string Name { get; set; }
}
So, it looks like the best (class can't be created without explicit init of Name field), but only for the first glance, because it's also 'syntax sugar', which uses only for compilation. So, when we map a property using automapper, we face with the same problem: object can be mapped without this property (or with null value from source object).
So, all of these approach only mask the problem (avoid warning compilation): object can be created with fake (default) value!
Any way to resolve this problem?
Thanks
If the property cannot be null, just put it in constructor, so there is no warning and must initialize the class with a valid value.