🔧 Fix a Primary Constructor Parameter Shadowed by a Field
A C# 12 primary constructor parameter is only captured into a compiler-generated backing field when something inside the class actually reads it from an instance member; until then, it behaves like an ordinary parameter in scope. Declare an explicit field with the exact same name as that parameter, and every reference to that name inside your instance methods resolves to the field you declared, not to the primary constructor’s captured value — the two coexist, but whichever one a given line of code happens to see depends on which declaration the compiler resolves first, which is easy to get backwards.
🔎 The Problem
public class Customer(string name)
{
private string name = name.Trim(); // explicit field, same name as
// the primary constructor parameter
public void Rename(string newName)
{
name = newName;
// Assigns the explicit FIELD - fine here, this is what you want.
// But anywhere else in the class that references "name" is also
// reading/writing that SAME field, not a separately captured
// primary-constructor value - there's only ever one "name" in
// scope once the field is declared, which can be surprising if
// you expected the raw constructor argument to still be reachable
}
}
✅ Fix: A Primary Constructor Parameter Shadowed by a Field
- Give the explicit field a distinct name (the common convention is a leading underscore, `_name`) whenever you need both the primary constructor’s raw parameter and a transformed or validated version stored separately.
- If you only need the transformed value and never the raw parameter again, that’s exactly what the shadowing field pattern above is for — just name it deliberately so a future reader knows it’s intentional, not an accident of matching names.
- Search for any primary constructor parameter name that’s reused as a field or property name elsewhere in the same class before assuming the parameter is still directly reachable everywhere in the class body.
🚨 Why This Is Dangerous
- Code review easily misses this, since both the parameter and the field share a name and the type system never complains — the only sign something’s off is behavior that doesn’t match what the constructor argument was supposed to do.
A primary constructor parameter only has one chance to be captured as-is — declare a field with the same name, and from then on, the field is the only one anybody’s talking to.



