🔧 C#: Fix a Required Member Compiling Without a Setter Call
The required modifier on a property is enforced entirely by the compiler at the call site of an object initializer, verifying that every required member appears somewhere in the braces, with no runtime enforcement of its own. A constructor marked with SetsRequiredMembers tells the compiler to trust that the constructor has already satisfied every required member internally, suppressing the initializer check entirely for any caller who uses it, so if the constructor’s body doesn’t actually set every required property, the object is constructed successfully with those properties left at their default values and nothing anywhere catches the omission.
🔎 The Problem
public class Order
{
public required string CustomerId { get; init; }
public required string ShippingAddress { get; init; }
[SetsRequiredMembers]
public Order(string customerId)
{
CustomerId = customerId;
// ShippingAddress never set here - but
// [SetsRequiredMembers] tells the compiler to trust
// this constructor satisfied every required member,
// so `new Order("cust-1")` compiles cleanly and
// ShippingAddress is silently null at runtime
}
}
✅ Fix: Treat the Attribute as an Unverified Promise
- Treat
[SetsRequiredMembers]as a manual promise the compiler can’t verify, and set every single required property inside that constructor’s body, since the attribute only turns off the compiler’s own check rather than confirming anything was actually assigned. - Add a unit test that constructs the object via the attributed constructor and asserts every required property is non-default, specifically because this is exactly the gap no compiler warning will ever catch.
- Prefer a plain object initializer without
[SetsRequiredMembers]wherever possible, reserving the attribute only for constructors that genuinely need to set required members from internal logic rather than from caller-supplied arguments.
🚨 Why This Is Dangerous
- A required property exists specifically to turn a missing value into a compile-time error instead of a runtime null-reference exception, and SetsRequiredMembers can quietly reopen exactly that hole for any constructor that doesn’t actually keep its promise.
required moves a null check from runtime to compile time, but only for callers using the initializer — a constructor marked SetsRequiredMembers is a promise the compiler stops checking.




