Constructors and object initializers
A constructor makes sure an object is valid from the moment it is created: it asks for the required data and checks it. Object initializers set optional values, and primary constructors (C# 12) keep simple classes short.
12.1 The problem: an invalid order
C#
var order = new Order();order.Total = 1499;Console.WriteLine($"Order #{order.Id} for '{order.Customer}'");Console.WriteLine($"Total: {order.Total}");Console.WriteLine($"Placed: {order.PlacedOn:yyyy-MM-dd}"); class Order{ public int Id { get; set; } public string Customer { get; set; } = ""; public decimal Total { get; set; } public DateTime PlacedOn { get; set; }}Output
$ dotnet run Order.csOrder #0 for ''Total: 1499Placed: 0001-01-01- No constructor written -> the compiler adds a hidden parameterless (default) constructor.
- It leaves every property at its default: Id 0, Customer empty, PlacedOn 0001-01-01.
- Nothing is checked, so an invalid order is created without any error.
12.2 Parameterized constructor
- Same name as the class, no return type at all.
- Takes the required data (id, customer) and validates it: ArgumentException.ThrowIfNullOrWhiteSpace(customer).
- Get-only properties ({ get; }) can be set only inside the constructor, so nobody changes them later.
C#
var order = new Order(101, "Asha");Console.WriteLine($"Order #{order.Id} for {order.Customer}");var bad = new Order(102, " "); class Order{ public int Id { get; } public string Customer { get; } public Order(int id, string customer) { ArgumentException.ThrowIfNullOrWhiteSpace(customer); Id = id; Customer = customer; }}Output
$ dotnet run Order.csOrder #101 for AshaUnhandled exception. System.ArgumentException: The value cannot be an empty string or composed entirely of whitespace. (Parameter 'customer')12.3 Constructor chaining with this
- Two constructors (customer only, or customer + delivery) should not copy the same validation.
- : this(customer, "Standard") forwards the short constructor to the bigger one.
- Validation and assignments live in one place; the chained target body runs first.
C#
var a = new Order("Asha");var b = new Order("Ravi", "Express");Console.WriteLine($"{a.Delivery}, {b.Delivery}");class Order{ public string Customer { get; } public string Delivery { get; } public Order(string customer) : this(customer, "Standard") { } public Order(string customer, string delivery) { ArgumentException.ThrowIfNullOrWhiteSpace(customer); Customer = customer; Delivery = delivery; }}Output
$ dotnet run Order.csStandard, Express12.4 Static constructor: runs once
- For one-time class-level setup (e.g. loading the GST rate), not per object.
- No access modifier, no parameters; you cannot call it yourself.
- The runtime calls it automatically once, before the first use of the class.
- If it throws, the whole type becomes unusable (TypeInitializationException), so keep it light.
C#
Console.WriteLine("App start");var a = new Invoice(1000);var b = new Invoice(500);Console.WriteLine($"{a.Tax} {b.Tax}");class Invoice{ static readonly decimal GstRate; static Invoice() { Console.WriteLine("Loading GST rate..."); GstRate = 0.18m; } public decimal Tax { get; } public Invoice(decimal amount) => Tax = amount * GstRate;}Output
$ dotnet run Invoice.csApp startLoading GST rate...180.00 90.0012.5 Object initializer
- A short way to set optional properties right after the constructor, inside { }.
- Works well with init properties: they can be set only during creation.
- Rule: required data -> constructor, optional data -> initializer.
C#
var o = new Order("Asha"){ Note = "Gift wrap", Coupon = "DIWALI10"};Console.WriteLine($"{o.Customer} | {o.Note}");Console.WriteLine($"Coupon: {o.Coupon}"); class Order{ public string Customer { get; } public string? Note { get; init; } public string? Coupon { get; init; } public Order(string customer) => Customer = customer;}Output
$ dotnet run Order.csAsha | Gift wrapCoupon: DIWALI1012.6 How it works: what runs when you write new
- Step 1
1.Static constructor (first use of the class only)
- Step 2
2.Field initializers
- Step 3
3.Chained this(...) constructor body
- Step 4
4.Constructor body
- Step 5
5.Object initializer sets Note, Coupon
An initializer can overwrite a constructor value, but inside the constructor the initializer values are not set yet
12.7 Checkpoint: chaining + static order
C#
new Order("Asha");new Order("Ravi"); class Order{ static Order() => Console.WriteLine("static"); public Order(string customer) : this(customer, "Standard") => Console.WriteLine("short"); public Order(string customer, string delivery) => Console.WriteLine("full");}Output
$ dotnet run Quiz.csstaticfullshortfullshort- static prints only once, for the first order.
- With chaining the target (full) body runs before the caller (short) body.
12.8 Primary constructor (C# 12)
- Parameters written next to the class name: class Order(string customer, decimal total).
- They are in scope in the whole class body (property initializers, methods).
- Every other constructor must chain to the primary one with : this(...).
C#
var a = new Order("Asha", 1000);var b = new Order("Ravi");Console.WriteLine($"{a.Customer}: {a.WithGst()}");Console.WriteLine($"{b.Customer}: {b.WithGst()}"); class Order(string customer, decimal total){ public string Customer { get; } = customer; public Order(string customer) : this(customer, 0) { } public decimal WithGst() => total * 1.18m;}Output
$ dotnet run Order.csAsha: 1180.00Ravi: 0.0012.9 Comparison: ways to set values at creation
| Feature | Syntax | Best for |
|---|---|---|
| Parameterized constructor | new Order(101, "Asha") | Required data + validation |
| Chaining | Order(string c) : this(c, "Standard") | Many constructors, one logic |
| Static constructor | static Order() { } | One-time class setup |
| Object initializer | new Order("Asha") { Note = ... } | Optional / init properties |
| Primary constructor | class Order(string customer) | Simple classes and services |
12.10 Common mistakes
- Writing your own constructor removes the hidden default one: new Order() -> error CS7036. Add public Order() : this("Guest") { } if you need it.
- Thinking primary constructor parameters become public properties: in a class they don't (a.total -> CS1061) and they are not readonly; create a property yourself. Records do generate them.
- Copying validation into every constructor instead of chaining with this.
- Doing heavy or risky work in a static constructor.
C#
var guest = new Order();Console.WriteLine(guest.Customer); // Guest class Order{ public string Customer { get; } public Order(string customer) => Customer = customer; public Order() : this("Guest") { }}12.11 5 rules for constructors
- Take required data through the constructor and validate it there.
- Multiple constructors: chain them with this to one main constructor.
- Static constructor: one-time, light setup only.
- Optional values: object initializer.
- Simple classes and services: primary constructor.
12.12 Interview tips
- Constructor chaining: one constructor calls another with : this(...) so validation and setup stay in one place.
- Static constructor: no parameters, no modifier, called by the runtime once before the first use of the class.
- Order on new: static constructor, field initializers, constructor body (chained target first), object initializer.
- Primary constructor parameters are captured parameters, not properties (unlike records).