skip to content

Constructors and Initialization

Field initializers run before the base constructor, static constructors run once, and primary constructors capture parameters. Interviewers ask about initialization order.

on this pageshow

explore

questions

6

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.
open as a page

In C#, when new creates a derived class, in what order do the derived and base field initializers and the two constructor bodies run?

level: middleimportance: must knowfreq 72%

basics

~20 s

Derived field initializers run first, then the base(...) arguments are evaluated, then the base class's field initializers, the base constructor body and finally the derived constructor body. An object initializer, if present, runs after all of them.

open as a page

In C#, when does an object initializer such as new FulfilmentOrder("ORD-7") { Quantity = 3 } assign its members, relative to the constructor?

level: juniorimportance: should knowfreq 58%

basics

~20 s

After the constructor returns. The compiler builds the object into a hidden temporary, assigns the members in textual order, and stores the reference in your variable only after every assignment succeeds, so the constructor sees default values.

open as a page

In C#, when does a class's static constructor run, how many times, and what happens to the type when it throws?

level: middleimportance: should knowfreq 52%

basics

~20 s

The runtime runs a static constructor at most once, just before the first instance is created or a static member is referenced. If it throws, the type stays uninitialized and every later use throws TypeInitializationException wrapping the original exception.

open as a page

A C# order-fulfilment service rewritten with a C# 12 primary constructor warns CS9124 on its feeCents parameter; what did the compiler generate, and what breaks?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Because feeCents is read in methods, the compiler captures it in a hidden, mutable field, while the FeeCents property initializer copies it into a second field. CS9124 warns about the two copies, which diverge once a method assigns the parameter.

open as a page

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%

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.

open as a page