skip to content

In C#, why does new HotelBooking("Ana Ruiz") still fail with CS9035 when that constructor assigns the required GuestName, and what does [SetsRequiredMembers] change?

level: seniorimportance: should knowfreq 40%

answer

  1. checked where the object is created
  2. constructor bodies are not inspected
  3. an attribute switches the check off
  4. nothing verifies the promise
  5. chaining constructors need it too

basics

~20 s

The required check runs at each creation site and never looks inside constructor bodies, so callers must still set every required member. [SetsRequiredMembers] declares that the constructor sets them all and switches the check off, without verifying it.

solid answer

~40 s

`required` (C# 11) is enforced where the object is created: for each `new`, the compiler looks only at whether the chosen constructor carries `[SetsRequiredMembers]` from `System.Diagnostics.CodeAnalysis`. If it does not, every required member must appear in the object initializer, otherwise CS9035, whatever the constructor body assigns. Adding the attribute turns the check off for that constructor entirely, and the compiler does not confirm the body sets anything. With nullable reference types on, an unassigned non-nullable `string` still draws CS8618 on that constructor, but a forgotten `DateOnly CheckIn` silently stays `0001-01-01`. A constructor that chains to an attributed one with `this(...)` or `base(...)` must carry the attribute too (CS9039). Put it only on constructors that really assign every required member.

code

csharp · 20 lines
csharp
using System.Diagnostics.CodeAnalysis;

var viaInitializer = new HotelBooking { GuestName = "Ana Ruiz", CheckIn = new DateOnly(2026, 11, 2) };
var viaConstructor = new HotelBooking("Ana Ruiz");   // compiles: the attribute vouches for every required member

Console.WriteLine($"{viaInitializer.GuestName} {viaInitializer.CheckIn:yyyy-MM-dd}");
Console.WriteLine($"{viaConstructor.GuestName} {viaConstructor.CheckIn:yyyy-MM-dd}");   // CheckIn never set

// var broken = new HotelBooking();   // error CS9035: GuestName and CheckIn must be set

public class HotelBooking
{
    public required string GuestName { get; init; }
    public required DateOnly CheckIn { get; init; }

    public HotelBooking() { }

    [SetsRequiredMembers]
    public HotelBooking(string guestName) => GuestName = guestName;   // forgets CheckIn: no diagnostic
}

go deeper

for a junior

Recall that required members must be set in the object initializer of every new expression, and that CS9035 names the member a caller forgot.

for a middle

Explain why the check happens at the creation site, how SetsRequiredMembers exempts a constructor, and why required does not imply non-null.

for a senior

Show the failure mode of an attributed constructor that forgets a value-type member, and how chaining (CS9039) and new() constraints (CS9040) interact with the attribute.

for a principal

Weigh required against constructor parameters for a shared type: adding required breaks existing callers at compile time, which is the safety you want, so it belongs in a planned release.

## What `required` means The **`required` modifier** (C# 11) marks a field or property that every creation of the type must assign. It closes a gap left by `init`: an `init` property *can* be set in an object initializer, but nothing forces the caller to do it. - A required member must be assigned in the **object initializer** of each `new` expression, unless the constructor used says it handles them. - Required properties need a `set` or `init` accessor at least as visible as the type (CS9034 "must be settable", CS9032 for a less visible member or setter). - `required` is not "non-null": `GuestName = null` satisfies the requirement, and only nullable analysis warns (CS8625). - A derived class cannot hide a required member (CS9031), and an override of one must keep `required` (CS9030). ## Why the constructor body does not count The compiler checks `required` **at the call site**, not by analysing constructors. When it binds `new HotelBooking("Ana Ruiz")`, it asks one question about the selected constructor: does it carry `System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute`? If not, the list of required members still has to be satisfied by the object initializer. A constructor that dutifully assigns `GuestName = guestName;` does not change that, so the call fails: `error CS9035: Required member 'HotelBooking.GuestName' must be set in the object initializer or attribute constructor.` This keeps the rule cheap and predictable across assemblies: the caller's compiler only needs the constructor's metadata, never its body. ## `[SetsRequiredMembers]` is an unchecked promise Applying the attribute to a constructor tells the compiler: "this constructor initializes all required members". The C# documentation warns that it **disables** the check, and the compiler does not verify the claim. In practice: 1. Callers using that constructor need no object initializer for required members. 2. A required member the constructor forgets keeps its default value. A forgotten `DateOnly CheckIn` reads `0001-01-01` with no diagnostic at all. 3. For a non-nullable reference type such as `string`, nullable analysis still reports CS8618 on the constructor ("Non-nullable property 'GuestName' must contain a non-null value when exiting constructor"); this is the nullable warning, not a required-members check, and it disappears when nullable reference types are off. 4. A constructor that chains to an attributed one with `this(...)` or `base(...)` must also carry it, or CS9039: "This constructor must add 'SetsRequiredMembers' because it chains to a constructor that has that attribute." ## Other rules worth knowing | Situation | Result | |---|---| | `new HotelBooking()` without the members in an initializer | error CS9035, once per missing member | | A type with required members as `T` in `where T : new()` | error CS9040, unless its parameterless constructor carries `[SetsRequiredMembers]` | | A constructor chaining to an attributed one without the attribute | error CS9039 | | A required property with no setter | error CS9034 | | A `protected` required member in a `public` class | error CS9032 | ## Reviewing the hotel booking class The scenario: callers were creating half-built `HotelBooking` objects, so the team marked `GuestName` and `CheckIn` as `required`. A sensible review checks: - **Adding `required` breaks source**: every existing `new HotelBooking()` without those members in an initializer now fails with CS9035, which is the intended effect, but it is a breaking change for a shared library's callers. - **Every `[SetsRequiredMembers]` constructor assigns every required member**, value types included, because nothing else will catch a miss. - **Constructors without the attribute are deliberate**: they force callers to use an initializer as well, which is legal but rarely what the author meant. - **Nullable reference types are enabled**, so a `required string` set to `null` at least produces a warning. Used this way, `required` plus `init` gives object-initializer syntax with a compile-time guarantee that callers supplied each value, while constructors remain available for callers who prefer them. ## `required` or a constructor parameter? Both make a caller supply a value; they differ in how the call reads and what the compiler checks: - a **constructor parameter** is positional, checked by overload resolution, and its assignment is visible in one place, the constructor body; - a **required member** is named at the call site (`GuestName = ...`), which reads well for types with many values, and adding an optional member later does not create a new constructor overload; - a constructor can validate several values together, for example that `CheckOut` is after `CheckIn`; `required` only checks presence, so cross-member rules still need a constructor, a `set` or `init` accessor, or a validation method.

  • Can a required string property be set to null?
    Yes. `required` means the member must be assigned, not that the value is non-null: `new HotelBooking { GuestName = null, CheckIn = default }` compiles, and with nullable reference types enabled the null literal draws warning CS8625. Pair `required` with a non-nullable type and treat nullable warnings as errors when null must be impossible.
  • Why can a type with required members not satisfy a new() constraint?
    Generic code that calls `new T()` has no object initializer through which to set the required members, so using `HotelBooking` as such a `T` is error CS9040. A parameterless constructor marked `[SetsRequiredMembers]` makes the type acceptable again, because that constructor claims to set every required member itself.
  • Can a derived class remove required from a property it overrides?
    No. An override of a required property must also be `required` (CS9030), and a derived class cannot hide a required member with `new` (CS9031). A derived type can add `required` when it overrides a property, so requirements only accumulate down a hierarchy.

A front desk that normally checks each guest's passport at check-in, unless a travel agent's voucher is stamped 'all documents verified'. The stamp skips the desk's check entirely, and nobody confirms the agent really looked, so a missing document is only discovered later.

  • Assigning the required member in the constructor body satisfies the requirement.
  • [SetsRequiredMembers] makes the compiler verify that the constructor assigns every required member.
  • A required string property can never hold null.
  • Adding required to an existing public property cannot break any caller.
  • init and required mean the same thing.