🔧 C#: Fix a Struct’s Default Constructor Skipping Field Defaults
C# 10 allows a struct to define its own parameterless constructor, but that constructor only runs when code explicitly calls new MyStruct(). Both default(MyStruct) and array allocation like new MyStruct[5] bypass it entirely and zero-initialize the memory directly, which means any field default or setup logic written inside that constructor simply never runs for a struct that arrives through either of those two very common paths.
🔎 The Problem
public struct Money
{
public string CurrencyCode;
public Money() { CurrencyCode = "USD"; }
}
var a = new Money(); // CurrencyCode == "USD" - constructor ran
var b = default(Money); // CurrencyCode == null - constructor skipped
var c = new Money[3]; // every element's CurrencyCode == null too
✅ Fix: Treat the Zeroed State as a Real Case, Not an Edge Case
- Don’t rely on the parameterless constructor to guarantee an invariant that must hold everywhere;
defaultand array allocation both skip it, and plenty of generic code (including some collections and serializers) produces structs exactly that way. - Where a field’s zero/null value isn’t a safe default, read it defensively at the point of use (treating null or zero as “not yet set” and resolving it there) instead of assuming the constructor already handled it.
- If a type genuinely needs a parameterless-constructor guarantee that holds no matter how it’s created, that’s a sign it should be a class, not a struct — classes don’t have a zero-initialized default state that bypasses their constructor the way structs do.
🚨 Why This Is Dangerous
- Code that works perfectly in every explicit
new Money()call site and only fails once aMoney[]array or a genericdefault(T)path is involved can pass all of its direct unit tests while still shipping a real, reachable bug.
A struct’s parameterless constructor is an invitation, not a guarantee —
defaultand array allocation are both perfectly entitled to decline it.
