C# Reference ยท Classes and Object-Oriented Concepts
Constructors
Reference for C# constructors: instance and static constructors, overloading, this(...) and base(...) chaining, default constructors, required members and order of execution.
A constructor is a special method that runs when an object is created. It has the same name as the class, no return type, and its job is to put the new object into a valid state. A class can have several constructors with different parameter lists (overloads), and one static constructor that initializes the type itself.
If you declare no constructor at all, the compiler provides a public parameterless one. As soon as you declare any instance constructor, that implicit one disappears.
public class Temperature { public double Celsius { get; } public Temperature(double celsius) => Celsius = celsius; public Temperature() : this(20) { } // chains to the other constructor }
Try it
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.
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.
Syntax
class C { static C() { } // static constructor: no access modifier, no parameters public C() { } // instance constructor public C(int x) : this() { } // chain to another constructor in this class public C(int x, int y) : base(x) { } // chain to a base constructor }
| Kind | Description |
|---|---|
| Instance constructor | Runs on every new. Can be public, protected, internal, private, and so on. |
| Static constructor | Runs once, before the first instance is created or any static member is accessed. Takes no parameters and has no access modifier. |
| Private constructor | Blocks creation from outside; used for singletons, factory methods and static-only helper classes. |
| Primary constructor | Parameters on the type declaration (C# 12). See Primary constructors. |
Copy / with |
Records have a compiler-generated copy constructor used by with. |
Errors: a constructor can throw; then new throws and the object is not handed out. An exception in a static constructor makes the type unusable and every later access throws TypeInitializationException.
Usage notes
- Order for
new Derived(): field initializers ofDerivedrun first, then the chosenbase(...)constructor (whose field initializers run just before its body), then the body of theDerivedconstructor. The second example shows that order. - Static constructors run once per type, lazily. In the second example
static Derived()printed beforestatic Base(), because creating aDerivedstarts its own type initialization first and the base type is initialized when the instance constructor chain reaches it. Do not depend on the relative order. - Calling virtual methods from a constructor is risky. The override may run before the derived part of the object is initialized.
- Constructor chaining (
: this(...)) puts validation and assignment in one place. Give the most complete constructor the real logic and let the others call it. - A base class without a parameterless constructor forces every derived constructor to call
base(...)explicitly. requiredmembers (C# 11) let callers satisfy initialization with an object initializer instead of constructor parameters. Mark a constructor with[SetsRequiredMembers]if it sets them itself.- Static constructors are for static state. Prefer static field initializers when they are enough; they are cheaper and safe from the type-initialization-order surprises of explicit static constructors.
- Validate arguments with
ArgumentNullException.ThrowIfNull(x)and similar helpers so an object is never created invalid. - Structs always have a parameterless constructor (C# 10 allows you to write your own); fields not assigned by it are zero-initialized.