Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The required modifier is a member-level keyword introduced in C# 11 that enforces the initialization of a field or property during object instantiation via an object initializer. It guarantees that a specific member is explicitly assigned a value by the caller before the object is fully constructed, shifting the initialization contract from the constructor to the call site.
public class Entity
{
    public required string Identifier { get; set; } // Required property
    public required DateTime CreatedAt;             // Required field
}

Compiler Enforcement

When a type contains required members, the C# compiler enforces their assignment at the point of allocation. Failure to initialize a required member in the object initializer results in compiler error CS9035.
// Valid: All required members are initialized
var entity = new Entity 
{ 
    Identifier = "ID-123", 
    CreatedAt = DateTime.UtcNow 
};

// Invalid: Compiler error CS9035 (CreatedAt is missing)
var invalidEntity = new Entity 
{ 
    Identifier = "ID-123" 
};

Constructor Interaction and [SetsRequiredMembers]

By default, no constructor satisfies the required constraint. Whether a constructor is parameterless or parameterized, invoking it requires the caller to use an object initializer for all required members. To instruct the compiler that a specific constructor internally handles the initialization of all required members, the [SetsRequiredMembers] attribute must be applied to that constructor. Safety Caveat: The C# compiler does not verify that a constructor marked with [SetsRequiredMembers] actually initializes the required members. It blindly trusts the attribute. If a developer applies this attribute but fails to assign the required fields or properties, the compiler will not emit any warnings or errors, potentially leading to uninitialized state at runtime.
using System.Diagnostics.CodeAnalysis;

public class User
{
    public required string Username { get; set; }

    // Standard constructor: Caller MUST use an object initializer
    public User() { } 

    // Attributed constructor: Caller is exempt from object initializer requirements
    [SetsRequiredMembers]
    public User(string username)
    {
        Username = username; 
    }

    // DANGER: The compiler blindly trusts this attribute. 
    // No error is thrown even though Username remains uninitialized.
    [SetsRequiredMembers]
    public User(int id) { }
}

// Usage:
var user1 = new User { Username = "admin" }; // Uses default constructor
var user2 = new User("admin");               // Uses SetsRequiredMembers constructor

Type System Rules and Constraints

  • Applicability: The required modifier can be applied to fields and properties within class, struct, and record types.
  • Settability: A required property must be settable. It must include either a set or init accessor. Applying required to a get-only property results in compiler error CS9031.
  • Visibility: The required member itself, as well as its set or init accessor, must be at least as visible as the containing type. The compiler enforces both conditions via a single compiler error (CS9032): “Required member '' cannot be less visible or have a less visible setter than the containing type.” For example, within an internal class, a public required property can legally possess an internal setter, but a private setter would trigger CS9032.
  • Generics: A type with required members cannot satisfy the new() generic constraint. Because the generic instantiation cannot know which required properties to initialize at the call site, attempting to use such a type for a new() constraint results in compiler error CS9040.
  • Nullable Reference Types (NRTs): Applying required to a non-nullable reference type suppresses compiler warning CS8618 (uninitialized non-nullable property). The compiler relies on the required contract to guarantee null safety at the call site rather than within the constructor.
  • Inheritance: Derived classes inherit the initialization requirements of base class required members. Furthermore, if a derived class constructor chains to a base class constructor that is marked with [SetsRequiredMembers], the derived class constructor must also be explicitly marked with [SetsRequiredMembers] (Compiler Error CS9041).
  • Interfaces: The required modifier cannot be specified in interface definitions. However, a class implementing an interface can mark the implemented members as required.
Master C# with Deep Grasping Methodology!Learn More