Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 182 ยท Classes and Objects

Constructors and Object Initialization

Learn C# constructors - default and overloaded constructors, this(...) chaining, static constructors, object and collection initializers, and the exact order in which an object is initialized.

When you write new Dog(), the runtime allocates memory for the object and then runs a special method that prepares it: the constructor. A constructor has the same name as the class, no return type, and its job is to make sure the new object starts life in a valid state. A Dog should never exist without a name; an Invoice should never exist with a negative total. Constructors are where you make those promises.

This lesson covers every kind of constructor you will meet: the implicit default one, your own overloads, chaining with this(...), static constructors, and the object and collection initializers that complement them. We finish with the exact order in which things happen, which is a favourite interview question and a source of real bugs.

The default constructor

If you write no constructor at all, the compiler gives your class a public parameterless one that does nothing special. That is why new Dog() worked in earlier lessons.

C# The implicit default constructor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Members that have no initializer get their default values (0, false, null). The moment you add any constructor of your own, the compiler stops generating the default one. If you still want to allow new Dog(), you must write it yourself.

Writing your own constructor

A constructor with parameters forces callers to provide the information the object needs:

C# A constructor with parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Two things to notice. First, the properties are read-only, so the constructor is the only place that can set them. Second, the constructor validates its input and throws if it is nonsense, so a Book with zero pages can never exist. Code that holds a Book never has to check again. This idea, making invalid states unrepresentable, is one of the best uses of constructors.

Overloaded constructors and this(...) chaining

A class may have several constructors with different parameter lists, called overloads. To avoid repeating validation code in each, make the simpler ones forward to one "main" constructor with : this(...).

C# Overloads that chain with this(...)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice the order in the output: the chained constructors run first (the main one prints its message), then the body of the constructor you actually called runs. Chaining keeps a single place for validation and avoids the classic bug where one overload forgets a check.

Do not create five overloads when one constructor with a few well-named optional parameters does the job: new Rectangle(width: 3, height: 4). Also consider static factory methods such as Rectangle.Square(5) when a name makes the intent clearer than a parameter list can.

Object initializers, again

Constructors work well for values that must be present. Optional extras are often nicer to set with an object initializer, which is not a constructor but runs right after one:

C# Constructor plus initializer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler turns the initializer into assignments that run after the constructor finishes. new Ticket("x") { Priority = 2 } is equivalent to creating the object, then writing t.Priority = 2;. That means the constructor cannot rely on those values, and that the properties must be settable (set or init). Combine required constructor arguments with optional initializer members and you get an API that is easy to read and hard to misuse.

Collection initializers

Types that implement IEnumerable and have an Add method accept collection initializers. The compiler calls Add for each entry. Dictionaries support the indexer form too.

C# Collection initializers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

For lists and arrays, prefer the newer collection expressions ([...]), but you will see the braces form in plenty of existing code.

Static constructors

A static constructor prepares the class itself, not an object. It has no access modifier and no parameters, and the runtime runs it automatically, exactly once, before the first instance is created or the first static member is used. You never call it.

C# A static constructor runs once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The static constructor message appears once, right before the first logger, not twice. Use static constructors for work like filling a lookup table. Keep them short and safe: if one throws, the type becomes unusable for the rest of the program (every use throws TypeInitializationException). For simple static values, a field initializer is usually enough: static readonly int Max = 100;.

The order of initialization

When you create an object whose class has a base class, a lot happens in a strict order. Understanding it explains why calling overridable methods from a constructor is dangerous.

C# Initialization order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Read the numbers in the output, not in the code: the run proves the order. For one object:

  1. The field initializers of the most derived class run first (this is a C# quirk: C# runs derived initializers first, unlike Java).
  2. Then the base class field initializers.
  3. Then the base constructor body.
  4. Then the derived constructor body.

If you write : this(...) the chained constructor runs its sequence first; if you write : base(...) the chosen base constructor runs. We cover this more in Inheritance.

Never call a virtual method from a constructor. The base constructor runs before the derived constructor, so an overriding method would execute on an object whose derived fields are not set up yet. It sees defaults (null, 0) instead of your values.

Private constructors and factory methods

A constructor can be private. Nobody outside can use new, so the class controls how instances are made, typically through a static factory method that can validate, cache or choose a subtype.

C# Private constructor and a factory method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A factory method has a descriptive name and can return null, a cached object, or a derived class. A constructor must always return a new instance of exactly that class. You will see the same idea in .NET itself: int.Parse, Guid.NewGuid(), TimeSpan.FromSeconds(5).

Common mistakes

  • Doing slow or risky work in a constructor. Connecting to a database or reading a file there makes the type hard to test and hard to use. Prefer a factory method or a separate InitializeAsync. Constructors cannot be async.
  • Forgetting that adding a constructor removes the default one. Then new Dog() stops compiling.
  • Duplicating validation across overloads. Chain with this(...).
  • Leaking this from a constructor. Passing the half-built object to other code (for example registering it in a list) lets them see it before it is finished.
  • Overly large parameter lists. More than four or five arguments is a hint to introduce a type for the group or use required properties with an initializer. See Properties.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens to the automatic parameterless constructor when you add your own constructor with parameters?

    The compiler only generates the default constructor when you declare none. Add your own and you must write the parameterless one if you want it.
  2. 2. What does : this(side, side) after a constructor declaration do?

    this(...) chains to another constructor in the same class, which avoids repeating initialization and validation code.
  3. 3. How many times does a static constructor run?

    The runtime runs it automatically exactly once per type (per process), before the first instance or static member access.
  4. 4. When does an object initializer such as new Ticket("x") { Priority = 2 } assign Priority?

    The initializer compiles to ordinary assignments that run after the constructor returns.
  5. 5. Why is calling a virtual method from a constructor risky?

    The base constructor runs before the derived constructor body, so the override can observe a partly built object.

Summary

  • A constructor prepares a new object; it has the class name and no return type.
  • The compiler provides a parameterless constructor only if you declare no constructors.
  • Overloads should chain with : this(...) so validation exists in one place.
  • Object initializers run after the constructor; collection initializers call Add (or use the indexer).
  • A static constructor runs once per type, automatically, before first use.
  • Initialization order: derived field initializers, base field initializers, base constructor, derived constructor.
  • Use private constructors and factory methods when a name, validation or caching helps; never call virtual members from a constructor.

Next: Primary Constructors