required modifier - C# reference (original) (raw)

Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

required modifier (C# Reference)

In this article

The required modifier indicates that the field or property it's applied to must be initialized by an object initializer. Any expression that initializes a new instance of the type must initialize all required members. The required modifier is available beginning with C# 11. The required modifier enables developers to create types where properties or fields must be properly initialized, yet still allow initialization using object initializers. Several rules ensure this behavior:

Some types, such as positional records, use a primary constructor to initialize positional properties. If any of those properties include the required modifier, the primary constructor adds the SetsRequiredMembers attribute. This indicates that the primary constructor initializes all required members. You can write your own constructor with the System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute attribute. However, the compiler doesn't verify that these constructors do initialize all required members. Rather, the attribute asserts to the compiler that the constructor does initialize all required members. The SetsRequiredMembers attribute adds these rules to constructors:

Warning

The SetsRequiredMembers disables the compiler's checks that all required members are initialized when an object is created. Use it with caution.

The following code shows a class hierarchy that uses the required modifier for the FirstName and LastName properties:

public class Person
{
    public Person() { }

    [SetsRequiredMembers]
    public Person(string firstName, string lastName) =>
        (FirstName, LastName) = (firstName, lastName);

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

    public int? Age { get; set; }
}

public class Student : Person
{
    public Student() : base()
    {
    }

    [SetsRequiredMembers]
    public Student(string firstName, string lastName) :
        base(firstName, lastName)
    {
    }

    public double GPA { get; set; }
}

For more information on required members, see the C#11 - Required members feature specification.

Collaborate with us on GitHub

The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.

Additional resources

In this article