C# Tip: Enforce Property Initialization with required
Use required properties to enforce initialization
public required string Name { get; init; }
The required modifier is a feature in C# that specifies that a particular field or property must be initialized when creating an instance of a class or struct. This is enforced through the use of an object initializer, which ensures that all necessary properties are set at the time of object creation.
When you use an object initializer to create a new instance, every required member must be given a value, ensuring that the object is in a valid state right from the start. This helps prevent runtime errors that can occur from accessing uninitialized properties.
The required modifier was introduced in C# 11, providing developers with a more robust way to enforce initialization rules and improve code reliability.
For more details, https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/required