Movatterモバイル変換


[0]ホーム

URL:


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.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit focus mode

required modifier (C# Reference)

  • 2023-01-31
Feedback

In this article

Therequired modifier indicates that thefield orproperty it's applied to must be initialized by anobject initializer. Any expression that initializes a new instance of the type must initialize allrequired members. Therequired modifier is available beginning with C# 11. Therequired 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:

  • Therequired modifier can be applied tofields andproperties declared instruct, andclass types, includingrecord andrecord struct types. Therequired modifier can't be applied to members of aninterface.
  • Explicit interface implementations can't be marked asrequired. They can't be set in object initializers.
  • Required members must be initialized, but they may be initialized tonull. If the type is a non-nullable reference type, the compiler issues a warning if you initialize the member tonull. The compiler issues an error if the member isn't initialized at all.
  • Required members must be at least as visible as their containing type. For example, apublic class can't contain arequired field that'sprotected. Furthermore, required properties must have setters (set orinit accessors) that are at least as visible as their containing types. Members that aren't accessible can't be set by code that creates an instance.
  • Derived classes can't hide arequired member declared in the base class. Hiding a required member prevents callers from using object initializers for it. Furthermore, derived types that override a required property must include therequired modifier. The derived type can't remove therequired state. Derived types can add therequired modifier when overriding a property.
  • A type with anyrequired members may not be used as a type argument when the type parameter includes thenew() constraint. The compiler can't enforce that all required members are initialized in the generic code.
  • Therequired modifier isn't allowed on the declaration for positional parameters on a record. You can add an explicit declaration for a positional property that does include therequired modifier.

Some types, such aspositional records, use a primary constructor to initialize positional properties. If any of those properties include therequired modifier, the primary constructor adds theSetsRequiredMembers attribute. This indicates that the primary constructor initializes all required members. You can write your own constructor with theSystem.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. TheSetsRequiredMembers attribute adds these rules to constructors:

  • A constructor that chains to another constructor annotated with theSetsRequiredMembers attribute, eitherthis(), orbase(), must also include theSetsRequiredMembers attribute. That ensures that callers can correctly use all appropriate constructors.
  • Copy constructors generated forrecord types have theSetsRequiredMembers attribute applied if any of the members arerequired.

Warning

TheSetsRequiredMembers disables the compiler's checks that allrequired members are initialized when an object is created. Use it with caution.

The following code shows a class hierarchy that uses therequired modifier for theFirstName andLastName 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 theC#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, seeour contributor guide.

Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo