Constructors and static members
A constructor
A constructor is the method that runs when new creates the object. It has the name of the class and no return type, it can take parameters, and it is the one place where a readonly field may be assigned. A field left without a value is zero or null, which is why a class that needs the value to be there takes it in the constructor:
var account = new Account("Anna", 100m);
account.Deposit(50m);
Console.WriteLine(account.Describe());
Console.WriteLine(account.Balance);
class Account
{
private decimal balance;
public Account(string owner, decimal opening)
{
Owner = owner;
balance = opening;
}
public string Owner { get; }
public decimal Balance => balance;
public void Deposit(decimal amount) => balance += amount;
public string Describe() => $"{Owner}: {balance:F2}";
}
dotnet run
Anna: 150.00
150
The interpolated line uses F2 and prints two decimals; the plain Console.WriteLine of the same decimal prints 150. A decimal keeps its scale from the literal 100m through the addition of 50m, and ToString() without a format drops the trailing zeros. Two ways of printing one number, and only one of them looks like money.
An object initializer
When a class has many optional values, an object initializer sets them by name after the constructor runs: new Ticket { Name = "Anna", Seat = 12 }. It needs settable properties, and init is the version that allows the assignment only during construction, so the object stays read-only afterwards.
var first = new Ticket { Name = "Anna", Seat = 12 };
var second = new Ticket { Name = "Borys", Seat = 4 };
Console.WriteLine($"{first.Name} seat {first.Seat}");
Console.WriteLine($"{second.Name} seat {second.Seat}");
Console.WriteLine($"tickets created: {Ticket.Created}");
class Ticket
{
public Ticket()
{
Created++;
}
public static int Created { get; private set; }
public string Name { get; init; } = "";
public int Seat { get; init; }
}
dotnet run
Anna seat 12
Borys seat 4
tickets created: 2
The initializer runs the parameterless constructor first, so Created counts both tickets. A static property belongs to the class rather than to an object: Ticket.Created is read from the type, and no instance is involved. Name has a default of the empty string, so a ticket built without a name is not null; Seat is a number that defaults to zero.
static members
A static member exists once per type, not once per object. Static fields hold shared state, static methods are called on the type, and a static constructor runs once, before the first use of the type.
- static readonly is a value that cannot be assigned after initialisation, but is computed when the type is first used.
- const is a compile-time constant: the value is copied into the calling code, so a library that changes it does not change an assembly that was not rebuilt.
- A static constructor has no parameters and no access modifier, and the runtime calls it once, on the first read of any static member.
const, static readonly and the order
The program below prints a constant and a static readonly value, and the static initialiser prints a line of its own, which shows when the runtime ran it:
Console.WriteLine($"const {Config.Name} limit {Config.Limit}");
Console.WriteLine($"again {Config.Limit}");
class Config
{
public const string Name = "app";
public static readonly int Limit = Compute();
private static int Compute()
{
Console.WriteLine("computing the limit");
return 42;
}
}
dotnet run
computing the limit
const app limit 42
again 42
computing the limit printed before the first line of output, because the first line reads Config.Limit and that read initialises the type. The second read printed nothing extra: the static field was computed once and keeps its value for the life of the process. A constant read does not trigger the initialiser at all, since its value is already in the calling code.
Exercises
- Give Account a constructor that takes only the owner and chains to the other one with : this(owner, 0m).
- Add a Seat check to Ticket that refuses zero in the constructor, and read the exception the initializer throws.
- Change const string Name to static readonly string and see whether the output order changes.
- Print Ticket.Created before the first ticket exists and explain which line of the static initialiser ran.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
When does a constructor run?
Answer
When new creates the object
new allocates the object and then runs the constructor before it returns the reference.
-
What does an object initializer do?
Answer
Sets properties by name after the constructor ran
The initializer is a sequence of assignments that follows the constructor call.
-
What does this program print?
var a = new C(); var b = new C(); Console.WriteLine(C.Count); class C { public C() { Count++; } public static int Count { get; private set; } }Answer
2
The static property is shared, so both constructors incremented the same counter.
-
How many times does a static constructor run?
Answer
Once, before the first use of any static member
The runtime guarantees one run of the type initialiser per application domain.
-
What is the difference between const and static readonly?
Answer
const is fixed at compile time, static readonly is set at run time
A const value is copied into the caller, a static readonly value is read from the type once.
-
Which assignment does
initallow?Answer
Only during construction or in an object initializer
An init accessor is writable while the object is being built, like a setter that closes afterwards.
-
What does this program print?
Console.WriteLine($"x{10m}y"); Console.WriteLine($"x{10.00m}y");Answer
x10y and then x10.00y
A decimal keeps the scale it was parsed with, and the default format prints it.
-
What happens to a field that no constructor assigns?
Answer
It keeps the default value: zero, false or null
Object memory is zeroed before the constructor runs, so an unassigned field has the type default.
-
Which member can a static method not use directly?
Answer
An instance field
There is no instance in a static context, so a field of this needs an object first.
-
Why give a class a parameterless constructor and init properties instead of one constructor with many parameters?
Answer
The call site names each value and the order cannot be mixed up
Named assignment makes a long list of arguments readable and lets the optional ones stay unset.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev