C# 11 required feature

It's possible to forget the initialization of properties when they are in bulk, to help with that, in C# 11 we have required keyword to be used with class fields or properties.

// Example of property
public required string Name {get;set;}

// Example of class field
public required int _marks;




In both cases, we will get a compiler error when we create an object of such a class without initializing those fields or properties.




This feature is very handy because there is always a chance to forget the initialization of fields or properties. This feature is in preview in C#11 to make it enable, you need to update your .csproj file.




Comments