A few years ago with the introduction of Nullable Reference Types in C# 8, I blogged about a way to get rid of the CS8618 compiler warning for your DTO’s and ViewModels. The trick I shared was to use a a property assignment with a default literal:
Although this solution works it defeats the point of nullable reference types, as the idea is it would help you to get rid of unexpected NullReferenceExceptions. Instead the only thing you got is a compiler that no longer complaints.
With the release of C# 11, a better solution exists through the usage of the required modifier.
The
required
modifier indicates that the field or property it's applied to must be initialized by all constructors or by using an object initializer.
Let’s update our code:
Now the compiler expects that the property is always set, so the compiler warning disappears.
Remark: The required
modifier is enforced at compile time. So it is still possible that we end up with a NullReferenceException
when for example the object is created through deserialization of a JSON document.