C# 11 - Required Keyword

Introducing the required keyword for fields and properties.

In C# 11, when a member is declared as required, the compiler will issue an error when the member is not set at creation:

var person = new Person { FirstName = "Tom", LastName = "Kazansky" };
// error: FirstName and LastName are not set
// var p = new Person();

class Person
{
public required string FirstName;
public required string LastName { get; init; }
}

ReSharper and Rider fully support the required keyword: it is recognized in your code and listed in code completion. They also provide code analysis and quick-fixes to initialize the required fields and properties.

See Also


Related Resources

C# 11 - Raw strings
There is no escape!
Use collection initializers
Update and initialize items in old collection declarations
Rename refactoring
Would a variable by any other name read as clearly?