🔧 Fix a Required Member Satisfied by the Wrong Initializer
A constructor marked with [SetsRequiredMembers] is a promise to the compiler that it assigns every required member the type declares – but the compiler never actually checks that the constructor’s body keeps that promise. It only checks that call sites using the plain object-initializer syntax set every required member; a constructor carrying the attribute gets a free pass to skip one entirely, and the required property it never touches is silently left at its type’s default, null for a reference type, instead of producing the compile error a plain initializer omitting it would.
🔎 The Problem
public class ShippingLabel
{
public required string RecipientName { get; init; }
public required string Address { get; init; }
public string? TrackingNumber { get; init; }
public ShippingLabel() { }
[SetsRequiredMembers]
public ShippingLabel(string recipientName)
{
RecipientName = recipientName;
// Address is required but never assigned here - the compiler
// takes [SetsRequiredMembers] as a promise and does not check
// that every required member actually got set inside this body
}
}
var label = new ShippingLabel("Ayse Yilmaz"); // compiles cleanly
Console.WriteLine(label.Address.Length); // NullReferenceException at
// runtime - Address was never
// actually required here
✅ Fix: Don’t Trust SetsRequiredMembers Blindly
- Treat [SetsRequiredMembers] as an unchecked promise rather than a verified guarantee – manually review every constructor carrying that attribute to confirm it genuinely assigns every required member the type declares, each time a required member is added or removed.
- Prefer the plain, attribute-free object initializer syntax for call sites wherever possible, since that path is fully compiler-checked against every required member with no way to opt out.
- Add a unit test that constructs the type through each [SetsRequiredMembers] constructor and asserts every required member has a non-default value afterward, so a future edit that adds a required property without updating an existing constructor fails a test immediately instead of surfacing as a null reference downstream.
🚨 Why This Is Dangerous
The entire point of required is to turn a missing-value bug into a compile error instead of a runtime one – but SetsRequiredMembers creates exactly one path back to the old behavior, and because it still compiles without warning, a reviewer has no compiler signal telling them to double-check that particular constructor’s body by hand.
required only protects the call sites the compiler actually checks – and SetsRequiredMembers is the one place it was explicitly told to stop checking.



