skip to content

A C# Notification base constructor calls a virtual BuildHeader that SmsNotification overrides; why does the override see a null phone number, and how do you fix it?

level: seniorimportance: should knowfreq 48%

answer

  1. the object's type is final from allocation
  2. base body runs before derived body
  3. initializer vs constructor-body assignment
  4. CA2214

basics

~20 s

Virtual dispatch already reaches SmsNotification's override while Notification's constructor runs, but SmsNotification's constructor body has not run yet, so fields it assigns are still null. Pass the data to the base constructor or build the header after construction.

solid answer

~40 s

In C# an object has its final runtime type from allocation, so a virtual call made in the base constructor dispatches to the derived override. The order is: derived field initializers, then the base constructor body, then the derived constructor body. The override therefore sees initialized fields set but `_phone`, assigned in the `SmsNotification` constructor body, still `null`. Nullable analysis does not catch this; code analysis rule CA2214 does, though it is not enabled by default. Fix the design rather than the symptom: pass the needed values through `: base(...)`, compute the header lazily after construction, or use a factory that constructs first and then runs the virtual step.

code

csharp · 28 lines
csharp
var sms = new SmsNotification("+15550100");
Console.WriteLine(sms.Header);

abstract class Notification
{
    public string Header { get; }

    protected Notification()
    {
        Header = BuildHeader();          // virtual call from the base constructor
    }

    protected virtual string BuildHeader() => "notification";
}

class SmsNotification : Notification
{
    private readonly string _channel = "sms";   // field initializer
    private readonly string _phone;              // assigned in the constructor body

    public SmsNotification(string phone)
    {
        _phone = phone;
    }

    protected override string BuildHeader() =>
        $"{_channel} to {_phone ?? "<null>"} (length {_phone?.Length.ToString() ?? "?"})";
}

go deeper

for a junior

Recall that a constructor calling a virtual method can reach a derived override before the derived class has finished setting itself up.

for a middle

Explain the order: derived field initializers, base constructor body, derived constructor body, and why that makes initializer-set fields visible but constructor-set ones null.

for a senior

Diagnose it from a NullReferenceException whose stack shows a derived method under the base constructor, name CA2214, and fix the construction design rather than adding null checks.

for a principal

Set a rule for base classes in shared code: constructors call no overridable members, and extension points that need data receive it through constructor parameters or a factory.

## What happens `Notification`'s constructor calls `BuildHeader()`, a `virtual` method, and `SmsNotification` overrides it to include the phone number. Creating `new SmsNotification("+15550100")` produces a header with a null phone number; if the override dereferences `_phone` (for example `_phone.Substring(0, 3)`), the constructor throws a `NullReferenceException` whose stack trace shows `SmsNotification.BuildHeader` called from `Notification..ctor`, called from `SmsNotification..ctor`. Nothing is wrong with dispatch. The object is an `SmsNotification` from the moment memory is allocated, so **a virtual call from the base constructor already reaches the derived override**. The problem is timing: that override runs **before the derived constructor's body has executed**. ## The order that produces the bug The detailed order of construction belongs to the lesson on constructors and initialization; the part that matters here is short: 1. The derived class's **field initializers** run (`_channel = "sms"`). 2. Control passes to the base constructor through the implicit or explicit `base(...)` call. 3. The **base constructor body** runs, calls `BuildHeader()`, and virtual dispatch reaches `SmsNotification.BuildHeader`. 4. Only then does the **derived constructor body** run and assign `_phone`. So inside the override: - fields with **initializers** are already set, which is why `_channel` prints `sms`; - fields assigned in the **constructor body** still hold their default value, `null` for references and `0` for numbers; - `readonly` gives no protection, because the field really is unassigned at that moment; - a C# 12 primary constructor parameter that the override captures is stored before the base constructor runs, so it does read the argument. Do not rely on that as a design. ## Why the tools are quiet - **Nullable reference types** do not warn. Flow analysis checks that `_phone` is assigned by the end of the derived constructor, which it is; it does not model the base constructor calling back into the derived class before that point. - The rule that does flag it is the code analysis rule **CA2214**, "Do not call overridable methods in constructors". Its documentation lists it as not enabled by default in .NET 10; with `AnalysisMode` set to `All` the .NET 10 SDK reports it on the `BuildHeader()` call. Its guidance is not to suppress it but to redesign the constructor. ## Ways to fix it | Fix | How | Trade-off | |---|---|---| | Pass data up | `SmsNotification(string phone) : base(...)` with the header or its parts as constructor arguments; the base no longer calls out | Base constructor signature grows | | Build on first use | Header computed lazily in a property, after construction | First access does the work; not for invariants needed at once | | Factory and initialize | Private constructor plus a static `Create` that constructs, then calls the virtual step | Every caller must use the factory | | Make the step non-virtual | Base computes the header itself, subclasses supply data | Less flexibility for subclasses | When choosing, keep these in mind: - **Do not** fix it by making the override defensive (`_phone ?? ""`). The header is then built from incomplete state and silently wrong. - **Sealing** `SmsNotification` does not help: the call is in the base class, and the base class is still open to every derived type. - If a base type truly needs a derived customisation during construction, the customisation must depend only on constructor arguments, never on derived fields. ## Designing a base class that stays safe A base class that needs subclass input during construction can be written so the problem cannot arise: - Take everything the base constructor needs as **constructor parameters**, and let each derived constructor pass its values through `: base(...)`. Arguments are evaluated before the base constructor body runs, so they are complete. - Keep the **extension points** (`virtual` or `abstract` members) for behaviour that runs after construction: sending, formatting on demand, validation before use. - If a hook really must run once per object, run it from a factory method after `new` returns, or on first use, and document that it is not called from a constructor. - Enable **CA2214** in the shared codebase so a new violation shows up in review instead of in a production stack trace. ## How an interviewer probes it Expect follow-ups such as: what does the override see in a field that has an initializer, does it change if the field is `readonly`, which analyzer finds it, and why the nullable warnings stay silent. A strong answer separates the two facts cleanly: **dispatch** is already derived during the base constructor, and **initialization** of the derived constructor body has not happened yet.

  • Does it help to give _phone an initializer or mark it readonly?
    `readonly` changes nothing: the field is still unassigned when the base constructor calls out. An initializer would be visible, because derived field initializers run before the base constructor, but an initializer cannot read the constructor's `phone` argument. A C# 12 primary constructor parameter captured by the override is stored early enough to be seen, yet relying on that ordering is fragile; pass the value up instead.
  • Which tool reports this, and why does nullable analysis miss it?
    Code analysis rule CA2214, Do not call overridable methods in constructors, flags the virtual call in the base constructor; it is off by default and is enabled by raising its severity or setting `AnalysisMode` to `All`. Nullable flow analysis only checks that each constructor assigns its non-nullable fields before it returns; it does not track the base constructor calling back into a derived member early.

  • Says the base constructor calls the base BuildHeader because the derived part does not exist yet.
  • Thinks all derived fields are set before any base constructor code runs.
  • Fixes it with a null check in the override instead of changing the design.
  • Believes sealing the derived class stops the base constructor from calling its override.
  • Expects nullable reference type warnings to report the null field.