skip to content

Should a C# team adopt primary constructors for its service classes' dependencies, and what house rule and enforcement would you put around captured parameters?

level: principalimportance: should knowfreq 32%

answer

  1. less boilerplate, weaker guarantees
  2. captured means mutable
  3. where validation can live
  4. warnings the build can fail on

basics

~20 s

Adopt them where they remove boilerplate, but pick one storage rule: either allow captured parameters and forbid assigning them, or require each parameter to initialize a private readonly field. Enforce it with CS9124 and CS9107 as errors and IDE0290's settings.

solid answer

~40 s

Primary constructors (C# 12) remove the field-plus-constructor boilerplate that service classes repeat, but they trade away guarantees a classic constructor gives: a captured parameter is a mutable hidden field, there is no constructor body for validation, and naming conventions for fields stop applying. A workable house rule is one of two: **captured parameters allowed, never assigned**, which is concise but enforced only by review; or **every parameter initializes a `private readonly` field of the same name**, which keeps immutability, gives a place for `?? throw` validation and compiles with no capture. Keep classic constructors for types with multi-parameter invariants or several genuinely different constructors. Enforce with `WarningsAsErrors` for CS9124 and CS9107, and set `csharp_style_prefer_primary_constructors` and IDE0290's severity in `.editorconfig` so the IDE's suggestions match the rule.

code

csharp · 23 lines
csharp
var service = new FulfilmentService(new Inventory(), new Clock());
Console.WriteLine(service.Fulfil("ORD-12"));
try
{
    _ = new FulfilmentService(null!, new Clock());
}
catch (ArgumentNullException ex)
{
    Console.WriteLine($"{ex.GetType().Name}: {ex.ParamName}");
}

class Inventory { public bool Reserve(string orderId) => orderId.Length > 0; }
class Clock { public DateTime UtcNow => new(2026, 10, 10, 9, 0, 0, DateTimeKind.Utc); }

// House rule: primary-constructor parameters only initialize readonly fields.
class FulfilmentService(Inventory inventory, Clock clock)
{
    private readonly Inventory inventory = inventory ?? throw new ArgumentNullException(nameof(inventory));
    private readonly Clock clock = clock ?? throw new ArgumentNullException(nameof(clock));

    public string Fulfil(string orderId) =>
        inventory.Reserve(orderId) ? $"{orderId} reserved at {clock.UtcNow:HH:mm}" : $"{orderId} rejected";
}

go deeper

for a junior

Recall that primary constructors put a class's constructor parameters in its header and that the parameters can be used anywhere in the class.

for a middle

Explain captured versus uncaptured parameters, why a captured one is mutable, and what CS9124 and CS9107 report.

for a senior

Review conversions for lost readonly fields, lost validation and double storage, and fix each with one storage per value.

for a principal

Choose and document one rule for the codebase, weigh concision against compiler-checked immutability, and wire the build and editorconfig to enforce it.

## The decision a lead owns **Primary constructors** on classes arrived in **C# 12**. For service classes, the typical shape is a type that receives a handful of collaborators and keeps them for its lifetime, one of the uses the C# documentation itself illustrates. The language question is not whether the feature works but **how parameters are stored**, because the compiler's choice there is invisible at the use site. A house rule makes that choice explicit and reviewable. How a container supplies those parameters is a framework concern, covered with ASP.NET Core's dependency injection. ## What the team gains - **Less boilerplate**: no field declarations, no constructor body that only assigns them. - **Dependencies visible in the header**: a reader sees what the class needs on its first line. - **IDE support**: the code style rule IDE0290 ("Use primary constructor") suggests the conversion; its option `csharp_style_prefer_primary_constructors` defaults to `true`. ## What the team gives up - **Immutability by default.** A parameter used in a method is captured into a hidden field that is not `readonly`. Any method can write `inventory = null;` and the compiler says nothing. - **A constructor body.** Validation must move into field initializers (`= clock ?? throw new ArgumentNullException(nameof(clock))`) or disappear. - **Single storage.** A parameter used both in a member initializer and in a method is stored twice (warning CS9124); one passed to `base(...)` and also used in a method is stored twice across the hierarchy (warning CS9107). - **Naming conventions.** Captured parameters are camelCase names with no field prefix, so a team's `_field` convention no longer marks object state. - **Flexible overloads.** Every other constructor must chain to the primary one (CS8862). ## The options | Rule | Concise | Immutable | Validation site | Enforced by | |---|---|---|---|---| | A. Captured parameters, never assigned | Most | No, by convention only | None | Code review | | B. Each parameter initializes a `private readonly` field | Medium | Yes | Field initializer | Compiler (readonly) and review | | C. Classic constructors only | Least | Yes | Constructor body | Nothing new | Rule **B** is the usual compromise: the class keeps the short header, and the line `private readonly Clock clock = clock ?? throw ...;` both validates and stores the dependency. The field shadows the parameter outside initializers, so methods use the readonly field and nothing is captured; the example compiles with no warnings in that shape. Rule **A** suits teams whose services are small, reviewed carefully and never assign their dependencies. Rule **C** remains right for types where several parameters must be validated together, where constructors do real work, or for public library types whose constructor is part of a documented API. ## Enforcement 1. Fail the build on the double-storage warnings: `<WarningsAsErrors>CS9124;CS9107</WarningsAsErrors>`; with that setting the SDK reports `error CS9124` instead of a warning. The lesson on warnings and analyzers covers the mechanics. 2. Configure IDE0290 in `.editorconfig` so that its suggestion matches the rule; under rule C, set `dotnet_diagnostic.IDE0290.severity = none`. 3. Add a review checklist item for rule A: no assignment to a primary constructor parameter, because no compiler diagnostic reports one. 4. Convert existing classes incrementally, by hand or with the IDE fix, and review each diff: a conversion that turns a `readonly` field into a captured parameter weakens the class. ## How to decide - **Team size and turnover**: the more people touch a class, the more rule B's compiler-checked `readonly` is worth. - **Validation habits**: if constructors routinely guard their arguments, rule A loses that guard. - **Mixed language versions**: a codebase that also compiles with an older C# cannot use the feature there; a split rule may be simpler than a uniform one. - **Tooling**: reflection-based tools see captured parameters as compiler-named fields such as `<inventory>P`, while rule B's fields keep their declared names. - **Consistency over cleverness**: whichever rule wins, one rule per codebase is worth more than the best rule applied to half of it.

  • Why not simply enable IDE0290 everywhere and convert every constructor in one pass?
    A conversion that removes the old fields replaces `readonly` storage with captured, mutable parameters, and validation that lived in constructor bodies has nowhere to go. Convert incrementally and review each diff against the house rule.
  • When would you keep a classic constructor in a codebase that otherwise uses primary constructors?
    When several parameters must be validated together, when construction does real work beyond storing values, when a type needs several constructors with different logic, or when a public library type documents its constructor as API.

  • Primary constructors make dependencies immutable, so no rule is needed.
  • A captured parameter and a private readonly field compile to the same thing.
  • The compiler warns whenever a method assigns a primary constructor parameter.
  • Primary constructors exist only on records, so service classes cannot use them.

Assumes C# 14 on .NET 10; primary constructors on non-record classes date from C# 12, so a rule for them applies only to projects compiled with C# 12 or later.