In C#, when new creates a derived class, in what order do the derived and base field initializers and the two constructor bodies run?
answer
- initializers are not part of the body
- where the compiler places initializers
- before the call to the base constructor
- initializers climb up, bodies come down
basics
~20 sDerived 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.
solid answer
~40 sThe C# compiler copies a class's instance field initializers into the start of every constructor that does not chain with `: this(...)`, *before* that constructor calls its base constructor. So `new CsvExportPlugin()` runs the derived initializers, evaluates the `base(...)` arguments, enters the base constructor (which runs the base initializers, calls `object`'s constructor and then runs the base body) and only then runs the derived body. Initializers therefore run most-derived first, while constructor bodies run base first. Because an initializer runs before the object is fully built, the compiler rejects one that reads another instance field or calls an instance method (CS0236). An object initializer on the `new` expression runs after the whole chain has returned.
code
csharp · 39 linesvar plugin = new CsvExportPlugin();
Console.WriteLine($"Loaded {plugin.Name}");
static class Log
{
public static string Write(string message)
{
Console.WriteLine(message);
return message;
}
}
class PluginBase
{
private readonly string baseStamp = Log.Write("3. PluginBase field initializer");
public string Name { get; }
protected PluginBase(string name)
{
Log.Write("4. PluginBase constructor body");
Name = name;
}
}
class CsvExportPlugin : PluginBase
{
private readonly string derivedStamp = Log.Write("1. CsvExportPlugin field initializer");
public CsvExportPlugin() : base(PluginName("csv-export"))
{
Log.Write("5. CsvExportPlugin constructor body");
}
private static string PluginName(string name)
{
Log.Write("2. base(...) argument evaluated");
return name;
}
}go deeper
Recall the two directions: field initializers go from the derived class up, constructor bodies come from the base class down, and object initializers come last.
Explain that the compiler copies initializers into each constructor before the base call, why CS0236 exists, and where the base(...) arguments are evaluated.
Use the order to reason about failures: side effects in initializers that ran before a base constructor threw, and fields set in a derived body that base code cannot yet see.
Set guidance that keeps initializers to plain values and moves ordering-sensitive work into constructor bodies or factories, so reviewers can read the order off the code.
## What a C# constructor is compiled into A **field initializer** is the `= expression` written on a field or auto-property declaration, such as `private readonly string stamp = Log.Write("...");`. A **constructor body** is the block inside the constructor. C# has no separate "initialization phase" at run time: the compiler **copies every instance field initializer into the prologue of each constructor** of that class, in textual order, and places them **before** the call to the base class constructor. The only constructors that do not receive the initializers are those that chain to a sibling with `: this(...)`, because the sibling they reach will run them. So a constructor such as `public CsvExportPlugin() : base(PluginName("csv-export")) { ... }` is emitted roughly as: 1. run `CsvExportPlugin`'s field initializers, top to bottom; 2. evaluate the arguments of `base(...)`; 3. call the `PluginBase` constructor, which itself runs `PluginBase`'s initializers, then calls `object`'s constructor, then runs the `PluginBase` body; 4. run the `CsvExportPlugin` constructor body. ## The order across a hierarchy Before any of this, the runtime allocates the object with every field **zeroed** (`0`, `false`, `null`), so a field without an initializer simply keeps that value until some constructor body assigns it. Applying the prologue rule to every level of the hierarchy then gives the order interviewers ask about: - **Initializers run from the most derived class upward**: derived, then base, then the base's base. - **Constructor bodies run from the top down**: `object`, then the base, then the derived class. - The **`base(...)` arguments** are evaluated after the derived initializers and before anything in the base class. - An **object initializer** (`new CsvExportPlugin { Enabled = true }`) assigns its members only after the last constructor body has returned. | Step | What runs | Which class | |---|---|---| | 1 | Instance field initializers | Derived | | 2 | Arguments of `base(...)` | Derived | | 3 | Instance field initializers | Base | | 4 | Constructor body | Base | | 5 | Constructor body | Derived | | 6 | Object initializer assignments | Caller's `new` expression | The example below logs from each place. The numbers in the messages are the order the SDK printed. ## Why the language runs initializers first Running the derived initializers before the base constructor means that every field with an initializer already holds its value by the time any base code runs, so base code never sees such a field at its zero value. Fields assigned in the **derived constructor body**, however, are still `null` or `0` while the base constructor runs; what that means for a virtual method called from a base constructor is the subject of the lesson on overriding and hiding. ## What the compiler rejects in an initializer Because an initializer runs while the object is only partly built, C# restricts what it may touch: - Reading another instance field, property or method of the same object is an error: `CS0236: A field initializer cannot reference the non-static field, method, or property 'Plugin.name'`. - Static members are allowed, which is why the example routes logging through a static `Log.Write`. - Primary constructor parameters (C# 12) are allowed, since they are parameters, not members. If an initial value needs instance state, compute it in the constructor body instead. ## Where static constructors fit A **static constructor** is separate. The first time a type is used, the runtime runs its static field initializers and static constructor once, before that type's instance code. In a run on the .NET 10 SDK, the derived class's static constructor ran before the derived instance initializers, and the base class's static constructor ran later, just before the base class's instance initializers, when the base constructor was first called. The static-constructor question covers that in detail. ## Practical consequences - Side effects in initializers (logging, allocation, registration) happen **before** the base constructor, even if the base constructor then throws. - If the base constructor throws, the derived body never runs, and `new` returns no reference. - Assigning a field in both its initializer and the constructor body is legal; the body runs later, so the body's value wins. - In a chain that uses `: this(...)`, the initializers still run once, in the constructor that finally calls the base. - Keep initializers to simple values; put ordering-sensitive logic in constructor bodies, where the order is easy to read.
- Why can a C# field initializer not call an instance method of its own class?Initializers run before the base constructor, while the object is only partly built, so the compiler rejects any reference to an instance member with CS0236. Static methods and primary constructor parameters are allowed. Move the logic into the constructor body if it needs instance state.
- If the base constructor throws, which parts of the derived class have already run?The derived field initializers and the `base(...)` argument expressions have already run, along with the base initializers and part of the base body. The derived constructor body never runs and `new` returns no reference, but any side effects the initializers had, such as logging or registering, have already happened.
- Does a constructor body that assigns a field override the field's initializer?Yes. The initializer is emitted at the start of the constructor and the body runs after the base constructor returns, so an assignment in the body is the last write. Writing both is legal but usually a sign the initializer is redundant.
- Base class field initializers run before the derived class's field initializers.
- Constructor bodies run derived first, then base.
- Field initializers run after the constructor body has finished.
- A field initializer can call any instance method of its own class.
- Object initializer assignments run before the constructor body.