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
C# 11 - Raw strings
There is no escape!
File-scoped namespaces and types
File-scoped namespaces and types
Organize code better and reduce bugs by using file-scoped namespaces and objects.
C# Top-level statements
C# Top-level statements
Use top-level statements in C# to reduce boilerplate code.