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 in C# (introduced in C# 11) is a member-level constraint applied to properties and fields that mandates their explicit initialization during object creation. When a member is marked as required, the compiler enforces that any instantiation of the declaring type must set the member’s value using an object initializer, preventing the creation of partially initialized objects.

Syntax and Declaration

The required keyword is placed before the type specifier (e.g., string or DateTime) of a property or field. It is most commonly paired with the init accessor to enforce immutability after initialization, but it is fully compatible with standard set accessors and mutable fields.
public class Entity
{
    // Required property with init-only setter
    public required string Id { get; init; }

    // Required property with standard setter
    public required string DisplayName { get; set; }

    // Required field
    public required DateTime CreatedAt;
}

Compiler Enforcement

The C# compiler performs static analysis at the call site of the constructor. If an object is instantiated without initializing every required member in the object initializer block, the compiler emits error CS9035.
// Valid: All required members are initialized
var entity1 = new Entity 
{ 
    Id = "123", 
    DisplayName = "Admin", 
    CreatedAt = DateTime.UtcNow 
};

// Invalid: Compiler Error CS9035
// Required member 'Entity.DisplayName' must be set in the object initializer.
var entity2 = new Entity 
{ 
    Id = "456",
    CreatedAt = DateTime.UtcNow
};

Technical Rules and Constraints

  • Accessor Requirements: A required property must possess a set or init accessor. It cannot be applied to read-only properties (properties with only a get accessor).
  • Visibility: A required member and its set or init accessor must be at least as visible as the containing type itself. For example, a public class must have public setters for its required properties, regardless of the visibility of its constructors. Conversely, an internal class can validly have an internal setter for a required property, even if that class exposes a public constructor.
  • Interfaces: The required modifier is invalid within interface definitions. It is strictly an implementation detail of class, struct, and record types.
  • Inheritance: The required constraint propagates down the inheritance hierarchy. When instantiating a derived class, the object initializer must satisfy all required members declared in both the derived class and its base classes.

Constructor Interaction and [SetsRequiredMembers]

By default, the compiler does not analyze constructor bodies to verify if required members are assigned. If a parameterized constructor initializes the required members internally, the compiler will still demand an object initializer at the call site. To override this behavior, the constructor must be decorated with the [SetsRequiredMembers] attribute from the System.Diagnostics.CodeAnalysis namespace. This attribute instructs the compiler to bypass the object initializer enforcement when that specific constructor is invoked.
public class User
{
    public required string Username { get; init; }
    public required string Email { get; init; }

    // Default constructor still requires object initializers
    public User() { }

    // Suppresses the required object initializer constraint for this constructor
    [SetsRequiredMembers]
    public User(string username, string email)
    {
        Username = username;
        Email = email;
    }
}

// Valid: Uses [SetsRequiredMembers] constructor
var user1 = new User("admin", "admin@system.local");

// Valid: Uses default constructor + object initializer
var user2 = new User { Username = "guest", Email = "guest@system.local" };

Underlying Metadata (IL)

Under the hood, the required keyword is syntactic sugar that modifies the emitted Intermediate Language (IL). The compiler applies the System.Runtime.CompilerServices.RequiredMemberAttribute to the specific property or field. Additionally, it applies the System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute to the declaring type, ensuring that older compilers or languages that do not understand the required constraint will refuse to instantiate the type, thereby preserving type safety across assemblies.
Master C# with Deep Grasping Methodology!Learn More