skip to content

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%

answer

  1. it is not a constructor overload
  2. a hidden temporary variable
  3. the constructor sees defaults
  4. braces without new reuse the object

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.

solid answer

~40 s

An object initializer is syntax, not a constructor. `new FulfilmentOrder("ORD-7") { Quantity = 3, Discount = 5 }` is lowered to: call the constructor into a hidden temporary, assign `Quantity`, assign `Discount`, then copy the temporary into the target variable. So the constructor sees `Quantity` as `0`, and validation in the constructor cannot check members that the caller sets in braces. If a setter throws, the target variable is never assigned. Inside the braces, `Warehouse = { Code = "AMS-2" }` without `new` sets members on the object the property already holds, and `Tags = { "gift" }` calls `Add` on the existing collection; neither creates a new object, and both throw `NullReferenceException` if the property is null.

code

csharp · 46 lines
csharp
FulfilmentOrder? order = null;
try
{
    order = new FulfilmentOrder("ORD-7")
    {
        Quantity = 3,
        Warehouse = { Code = "AMS-2" },
        Tags = { "gift", "express" },
        Discount = -5,
    };
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine($"{ex.GetType().Name}; order is null: {order is null}");
}

class Warehouse
{
    public string Code { get; set; } = "unassigned";
}

class FulfilmentOrder
{
    private int discount;
    public string Id { get; }
    public int Quantity { get; set; }
    public Warehouse Warehouse { get; } = new();
    public List<string> Tags { get; } = new();

    public int Discount
    {
        get => discount;
        set
        {
            Console.WriteLine($"Discount setter: Quantity={Quantity}, Warehouse={Warehouse.Code}, Tags={Tags.Count}");
            ArgumentOutOfRangeException.ThrowIfNegative(value);
            discount = value;
        }
    }

    public FulfilmentOrder(string id)
    {
        Id = id;
        Console.WriteLine($"Constructor: Quantity={Quantity}, Warehouse={Warehouse.Code}");
    }
}

go deeper

for a junior

Recall that the constructor runs first and the braces assign members afterwards, in the order written.

for a middle

Explain the lowering to a hidden temporary, why the variable is assigned last, and the difference between Prop = new T { } and Prop = { }.

for a senior

Spot validation that wrongly lives in a constructor, and nested initializers on members that can be null.

for a principal

Decide which types take required data through constructors and which allow object initializers, so invariants are enforced consistently.

## What an object initializer is An **object initializer** is the `{ Member = value, ... }` block after a `new` expression. It is a **caller-side** feature: the type declares no special constructor for it, and the compiler turns it into ordinary member assignments after the constructor call. Any accessible settable field or property, or an `init` accessor, can appear in it. ## What the compiler generates For `order = new FulfilmentOrder("ORD-7") { Quantity = 3, Discount = -5 };` the compiler emits code equivalent to: 1. call `FulfilmentOrder(string)` and store the result in a **hidden temporary**; 2. assign `Quantity` on the temporary; 3. assign `Discount` on the temporary; 4. assign the temporary to `order`. Three consequences follow, and all three show in the example: - **The constructor runs first and sees default values.** The constructor printed `Quantity=0`. - **Assignments run in textual order.** The `Discount` setter already saw `Quantity=3`, the warehouse code and both tags. - **The target variable is assigned last.** When the `Discount` setter threw `ArgumentOutOfRangeException`, `order` was still `null`; the half-built object was never published through that variable. ## Nested initializers without new Inside an object initializer, a member can be followed by braces **without** `new`. The forms differ: | Syntax inside the braces | What it does | |---|---| | `Warehouse = new Warehouse { Code = "AMS-2" }` | Creates a new `Warehouse` and assigns it to the property | | `Warehouse = { Code = "AMS-2" }` | Reads the existing `Warehouse` and sets `Code` on it | | `Tags = { "gift", "express" }` | Reads the existing collection and calls `Add` once per element | The forms without `new` are what make a **get-only** property such as `public Warehouse Warehouse { get; } = new();` usable in an initializer: nothing is assigned to the property itself. The cost is that if the property is `null`, the nested initializer throws `NullReferenceException`. With nullable reference types enabled, the compiler flags the risk with warning CS8670, "Object or collection initializer implicitly dereferences possibly null member". ## Index initializers and init accessors The braces accept two more member forms that follow the same after-the-constructor rule: - An **index initializer** such as `new Dictionary<string, int> { ["AMS-2"] = 4 }` calls the indexer's setter on the new object, one call per entry, in order. - A property with an **`init` accessor** can be assigned here but not in a later statement; the details belong with fields and properties. Both still run on the hidden temporary, so the same rules about the constructor seeing defaults and the variable being assigned last apply. ## Where validation belongs Because the constructor runs before the braces, a constructor cannot validate values the caller sets in an initializer. That is the bug interviewers probe: a constructor that checks `Quantity > 0` throws for every caller who sets `Quantity` in braces, because the check still sees `0`. Options: - Take the value as a **constructor parameter** and validate it there. - Validate in the **setter**, as the example's `Discount` does with `ArgumentOutOfRangeException.ThrowIfNegative` (.NET 8). - Force callers to set a member with `required` (C# 11) and make it `init`-only; those rules belong to the lesson on fields and properties. ## Object initializers and other construction steps The full order for `new Derived(args) { X = 1 }` is: derived field initializers, base field initializers, base constructor body, derived constructor body, then the object initializer's assignments. A record's `with` expression looks similar but copies an existing object first; that is covered with nondestructive mutation. ## Pitfalls reviewers catch - Assuming the constructor can see initializer values. - Writing `Items = { ... }` on a property that may be `null`, expecting it to create the list. - Relying on the order of assignments for invariants between members, then reordering the braces. - Treating an initializer as atomic: earlier setters have already run, with their side effects, when a later one throws.

  • What does Warehouse = { Code = "AMS-2" } inside a C# object initializer do when Warehouse is null?
    It throws `NullReferenceException` at run time, because the form without `new` reads the existing object and sets `Code` on it; it never creates one. With nullable reference types enabled, the compiler warns CS8670 when the member may be null.
  • Why can a C# constructor not validate a property that callers set in an object initializer?
    The constructor finishes before any initializer assignment runs, so it sees the property's default value. Validate in the setter, take the value as a constructor parameter, or make the member required and init-only.

  • Object initializer assignments run before the constructor body.
  • Property = { ... } inside an object initializer creates a new instance.
  • If a setter throws, the target variable holds a half-initialized object.
  • An object initializer is a constructor overload the compiler generates on the type.