> ## 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.

# C# Required Field

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.

```csharp theme={"dark"}
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**.

```csharp theme={"dark"}
// 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.

```csharp theme={"dark"}
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 '{0}' 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`.

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor C# Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
