skip to content

In C#, how do the : this(...) and : base(...) constructor initializers chain constructors, and which mistakes does the compiler reject?

level: juniorimportance: must knowfreq 66%

answer

  1. one initializer per constructor
  2. the implicit call nobody wrote
  3. the chain must end at a base call
  4. no parameterless base, no implicit call

basics

~20 s

: this(...) forwards to another constructor of the same class; : base(...) picks a base-class constructor. Without either, C# inserts base(), so a base with no parameterless constructor gives CS7036. Field initializers run once, in the constructor that calls base.

solid answer

~40 s

A C# constructor may carry one constructor initializer. `: this(...)` delegates to another constructor of the same class, which runs first, then the calling body runs. `: base(...)` chooses which base constructor to call with which arguments. If you write neither, the compiler inserts `: base()`, and a class with no constructors gets a parameterless one that does the same, so deriving from a base whose only constructor takes arguments fails with CS7036 until you add `: base(...)`. Field initializers are emitted only in constructors that end at the base call, so a `this(...)` chain runs them once. The compiler rejects a constructor calling itself (CS0516), a cycle (CS0768), `this` in the arguments (CS0027) and reading instance fields there (CS0120).

code

csharp · 25 lines
csharp
var standard = new Shipment("ORD-1");
var express = new Shipment("ORD-2", priority: 3);
Console.WriteLine($"{standard.OrderId}: priority {standard.Priority}, stamp {standard.Stamp}");
Console.WriteLine($"{express.OrderId}: priority {express.Priority}, stamp {express.Stamp}");

class Shipment
{
    private static int initializerRuns;

    public int Stamp = ++initializerRuns; // field initializer
    public string OrderId { get; }
    public int Priority { get; }

    public Shipment(string orderId) : this(orderId, priority: 1)
    {
        Console.WriteLine($"Shipment(string) body, initializer runs: {initializerRuns}");
    }

    public Shipment(string orderId, int priority)
    {
        Console.WriteLine($"Shipment(string, int) body, initializer runs: {initializerRuns}");
        OrderId = orderId;
        Priority = priority;
    }
}

go deeper

for a junior

Recall what : this(...) and : base(...) each call, that the compiler inserts base() when you write neither, and that CS7036 means the base needs arguments.

for a middle

Explain the run order of a this(...) chain, why field initializers run once, and why the initializer arguments cannot use this or instance fields.

for a senior

Design overload chains that funnel into one complete constructor, and know when a private constructor with a static factory beats public overloads.

for a principal

Weigh constructor overloads against factories and primary constructors for a codebase's public types, and set one convention reviewers can enforce.

## Two kinds of constructor initializer In C#, a **constructor initializer** is the clause after the parameter list and before the body: - `: this(arguments)` calls **another constructor of the same class**. It is how overloads share one implementation instead of copying assignments. - `: base(arguments)` calls **a constructor of the direct base class** and chooses which overload, with which arguments. A constructor has **at most one** initializer. You cannot write both, and you cannot call a constructor from inside a body the way you call a method. Every chain of `this(...)` calls must therefore end at a constructor that calls `base(...)`, either explicitly or implicitly. ## The implicit base() call If a constructor has no initializer, the compiler inserts `: base()`. If a class declares **no constructors at all**, the compiler gives it a parameterless constructor that also calls `base()` (public for a non-abstract class). Both cases need the base class to have an accessible parameterless constructor. When it does not, the build fails: ```plaintext error CS7036: There is no argument given that corresponds to the required parameter 'name' of 'PluginBase.PluginBase(string)' ``` The SDK reports it on the derived constructor, or on the class name when the derived class declares no constructor. The fix is to declare a constructor with `: base(someName)`. ## Field initializers run once per object The compiler copies field initializers into the start of each constructor **that does not chain with `this(...)`**. In a chain `Shipment(string) : this(orderId, 1)` the initializers are emitted only in `Shipment(string, int)`, so they run once per object, and the order is: 1. the target constructor's prologue (field initializers, then the base call); 2. the target constructor's body; 3. the calling constructor's body. That is why the example's `Shipment(string, int)` body prints before the `Shipment(string)` body, and why `Stamp` increments once per object, not twice. ## What the compiler rejects The initializer's argument list runs before the object exists in any useful sense, so C# limits it. | Code in the initializer | Result on the .NET 10 SDK | |---|---| | `: this(...)` that calls the same constructor | CS0516: Constructor cannot call itself | | Two constructors calling each other through `this(...)` | CS0768: cannot call itself through another constructor | | `: base(this.ToString())` | CS0027: Keyword 'this' is not available in the current context | | `: base(prefix)` where `prefix` is an instance field | CS0120: An object reference is required | | `: base(DefaultName())` with a static method | Compiles | | Constructor parameters and constants | Compile | ## Private constructors and static factories Constructor access levels matter for chaining too. A `private` constructor can still be the target of `: this(...)` inside the class, and it is the usual partner of a **static factory method**: - `private OrderNumber(string value)` plus `public static OrderNumber Parse(string text)` lets the factory validate, normalize or return a cached instance before any constructor runs. - Outside the class, `new OrderNumber("x")` fails with `CS0122: 'OrderNumber.OrderNumber(string)' is inaccessible due to its protection level`. - A factory can have a descriptive name and can be `async`; a constructor can be neither. A `protected` base constructor is reachable from a derived class's `: base(...)` but not from `new` elsewhere. ## Primary constructors join the same rule Since C# 12, a class can declare a **primary constructor** in its header. Every other constructor of that class must then chain to it with `: this(...)`; one that does not fails with CS8862 ("A constructor declared in a type with parameter list must have 'this' constructor initializer"). The base call moves into the class header: `class AuditPlugin(string name) : PluginBase(name)`. ## Constructors are not inherited A derived class does **not** inherit its base class's constructors. If `PluginBase` has `PluginBase(string name)`, a `ReportPlugin` caller cannot write `new ReportPlugin("r")` until `ReportPlugin` declares its own constructor with that parameter and forwards it with `: base(name)`. Every overload the derived class wants to offer must be written out, which is exactly where `: this(...)` keeps the repetition down. ## Habits that keep chains readable - Point every overload at the **most complete** constructor and keep the logic there. - Prefer optional parameters only where the defaults are stable; the lesson on defaults, names and params covers that trade-off. - Keep `base(...)` arguments to parameters, constants and static helpers; anything else will not compile or will be hard to follow.

  • Why pair a private constructor with a public static factory method in C#?
    The factory can validate or normalize input, return a cached or derived instance, carry a descriptive name such as `FromCents`, or be `async`, none of which a constructor can do. The private constructor stops callers bypassing it: `new` from outside fails with CS0122.
  • Can a C# constructor call both this(...) and base(...)?
    No. A constructor has one initializer. A `this(...)` chain passes control to another constructor of the same class, and the last constructor in that chain makes the `base(...)` call, written or implicit.
  • What happens when two C# constructors call each other through this(...)?
    The compiler detects the cycle and reports CS0768, 'cannot call itself through another constructor'; a constructor that names itself directly gets CS0516. The chain must always end at a base call.

  • Without : base(...), C# calls no base constructor at all.
  • A class with no constructors compiles against any base class.
  • Field initializers run again for each constructor in a this(...) chain.
  • A constructor initializer's arguments can read the object's instance fields.
  • A constructor can call another constructor from its body like a method.