A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/required below:

required modifier - C# reference

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.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.3