Glossary / Constructors

Constructors

A constructor initializes a new instance and establishes its invariants. C# supports instance, static, primary, and parameterless struct constructors, with chaining through this or base-class initialization. Constructor design determines whether objects can exist in invalid or partially initialized states.

Execution and chaining

An instance constructor runs when an object is created. Instance field initializers execute as part of instance initialization before the constructor body; base and derived initialization order matters when virtual members or side effects are involved. : this(...) delegates to another constructor in the same type; : base(...) selects a base constructor. Overload resolution follows normal conversion rules and can become ambiguous with optional or null arguments.

public sealed class Range
{
    public int Start { get; }
    public int End { get; }
    public Range(int start, int end)
    {
        if (end < start) throw new ArgumentOutOfRangeException(nameof(end));
        (Start, End) = (start, end);
    }
}

A class with no declared constructor receives an implicit parameterless constructor subject to language rules. Structs always have a default value; default(T) is zero-initialized even if an explicit parameterless struct constructor exists. C# 12 primary constructors provide parameters usable throughout a class/struct body, but ordinary classes do not automatically gain properties from them as records do.

Design guidance

Validate inputs before publishing this. Avoid virtual calls from constructors because derived state may not be initialized. Keep constructors deterministic and lightweight; use factories for complex asynchronous resource acquisition.

Interview questions

  1. What is this chaining for? Reuse initialization logic among overloads.
  2. Why avoid virtual calls in constructors? Derived overrides can run before derived initialization completes.
  3. Can default(MyStruct) invoke its parameterless constructor? No; it yields zero-initialized value.
  4. Do primary constructors create properties? Not automatically for ordinary classes/structs.
  5. Where do field initializers fit? Before the constructor body, in the specified instance initialization sequence.

References