C# Constructors
A constructor is a special method that runs automatically when an object is created with new. Its job is to put the new object into a valid starting state — so that, for example, a BankAccount always has an owner and a Rectangle never has a negative width.
Declaring a constructor
A constructor has the same name as the class and no return type (not even void).
using System;
var car = new Car("Toyota", "Corolla", 2021);
Console.WriteLine(car.Describe());
class Car
{
public string Make;
public string Model;
public int Year;
public Car(string make, string model, int year)
{
Make = make;
Model = model;
Year = year;
}
public string Describe() => quot;{Year} {Make} {Model}";
}2021 Toyota Corolla
The default constructor
If you write no constructor at all, C# supplies an invisible parameterless constructor that leaves every field at its default value. As soon as you declare any constructor, that free one disappears — new Car() above would not compile.
Overloaded constructors and this(...)
A class can have several constructors with different parameters. To avoid duplicating code, one constructor can call another with : this(...):
using System;
var a = new Timer();
var b = new Timer(90);
var c = new Timer(2, 30);
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
class Timer
{
private readonly int totalSeconds;
public Timer(int seconds)
{
if (seconds < 0) seconds = 0;
totalSeconds = seconds;
}
public Timer(int minutes, int seconds) : this(minutes * 60 + seconds) { }
public Timer() : this(60) { }
public override string ToString() => quot;{totalSeconds / 60:D2}:{totalSeconds % 60:D2}";
}01:00
01:30
02:30
All roads lead to the single-parameter constructor, so the validation (seconds < 0) is written only once.
Validating arguments
Constructors are the perfect place to reject invalid data by throwing an exception. An object that could never be built in an invalid state is much easier to reason about.
using System;
var ok = new Temperature(-40);
Console.WriteLine(quot;Created {ok.Kelvin} K");
try
{
var bad = new Temperature(-300);
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine(quot;Rejected: {ex.ParamName}");
}
class Temperature
{
public double Kelvin { get; }
public Temperature(double celsius)
{
if (celsius < -273.15)
throw new ArgumentOutOfRangeException(nameof(celsius), "Below absolute zero");
Kelvin = celsius + 273.15;
}
}Created 233.14999999999998 K
Rejected: celsius
(The odd-looking 233.14999999999998 is ordinary floating-point rounding — remember decimal for exact decimal values.)
Primary constructors (C# 12)
For classes whose constructor only stores parameters, C# 12 lets you write the parameters directly after the class name. They are in scope throughout the class body:
using System;
var item = new OrderLine("Tea", 3, 4.5m);
Console.WriteLine(item.Summary());
class OrderLine(string product, int quantity, decimal unitPrice)
{
public string Product => product;
public decimal Total => quantity * unitPrice;
public string Summary() => quot;{quantity} x {product} = {Total}";
}3 x Tea = 13.5
Initialization order
When you write new Car(...):
- Memory is allocated and every field is set to its default value.
- Field initializers run (
private int count = 5;). - The base class constructor runs (see Inheritance).
- The body of your constructor runs.
Tip: Keep constructors short. Validate, assign and stop. Expensive work such as loading files is better done in a separate method the caller invokes explicitly.
Test yourself
What is the return type of a constructor?
- void
- The class type
- It has none
- object
A class declares only public Person(string name). What happens with new Person()?
- Name is set to null
- Name is set to ""
- Compile error — no parameterless constructor exists
- Runtime exception
What does : this(60) after a constructor's parameter list do?
- Calls the base class constructor
- Calls another constructor of the same class first
- Sets a field named this
- Creates a second object