Use the required Keyword in C# to Enforce Property Initialisation
Last week we saw how much code we can get rid of when we use the [init keyword to create immutable objects]. The only downside we found was that we cannot enforce that all properties get a value. To solve this problem, we can use the required keyword of C# 11:
The required modifier indicates that the field or property it is applied to must be initialized by an object initializer. Any expression that initializes a new instance of the type must initialize all required members. – from learn.microsoft.com
How to use the required keyword?
We can add the required keyword in the definition of our properties right after the access modifier as shown in this example:
That is all it takes to enforce that all required values are set at the object initialisation.
If we miss to set all values, we get this compiler error:
CS9035 Required member 'UserQuery.Person.LastName' must be set in the object initializer or attribute constructor.
Conclusion
With the init keyword of C# 9 we got a nice way to write less code for our immutable objects. But only with the addition of the required keyword in C# 11 we could ensure that all necessary values are set. This combination allows us now to keep the data integrity while we can profit from the improvements in C#.