Introducing C#11: Required properties


C# 11 improves the initialization of objects and struct. Marking one or more properties as mandatory on initialization is now possible and will help you not to forget to initialize your properties correctly. In this post I will show you how it works with the object initializer syntax and the object instantiation with a constructor.

Required properties in practical

Marking properties as required requites to add the required keyword on your properties as follow:

When initializing a car object, if you miss initializing a property, for example, the BrandId property, the compiler will raise the following error:

“Error CS9035 Required member ‘Car.BrandId’ must be set in the object initializer or attribute constructor.”

Using a constructor will lead to the same error if you don’t initialize all required properties. Otherwise, if you do not voluntarily initialize your required properties you will have to decorate your class with the SetsRequiredMembers attribute to avoid any compilation error, Examples:

Isn’t practical? 🙂 . I hope you won’t forget anymore your properties !

Written by


Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.
%d bloggers like this: