Constructors and invariants
A constructor establishes an object’s initial state. It has the same name as its class and no return type. An invariant is a condition that valid objects should maintain throughout their public lifetime, such as a quantity never being negative.
using System;Bin bin = new Bin(6);Console.WriteLine(bin.GetQuantity());class Bin{ private int quantity; public Bin(int quantity) { this.quantity = quantity; } public int GetQuantity() => quantity;}The constructor assigns the argument to the field. This first version initializes state but does not yet enforce a range.
Expected output (reasoned, not executed):
6Initialization and validation
A constructor accepts arguments and initializes fields or properties. If an ordinary non-static class declares no instance constructor, the compiler supplies a parameterless one (protected for an abstract class, public otherwise). Declaring an explicit instance constructor removes that automatic constructor. this refers to the current object, so this.quantity = quantity distinguishes a field from a parameter with the same name.
Constructor chaining and invalid input
Use : this(...) to delegate from one constructor to another in the same class. Centralizing validation reduces inconsistent initialization. A constructor may throw an exception to reject invalid input; the caller does not receive a successfully constructed reference from that expression. ArgumentOutOfRangeException is appropriate for a numerical argument outside its allowed range. The try/catch below is a preview: it handles the particular exception and continues; full exception handling comes later.
using System;try{ Bin invalid = new Bin(-1); Console.WriteLine(invalid.GetQuantity());}catch (ArgumentOutOfRangeException){ Console.WriteLine("Rejected");}Console.WriteLine(new Bin(0).GetQuantity());class Bin{ private readonly int quantity; public Bin(int quantity) { if (quantity < 0) throw new ArgumentOutOfRangeException(nameof(quantity)); this.quantity = quantity; } public int GetQuantity() => quantity;}The negative input throws before initialization succeeds. Zero is valid. readonly prevents later field reassignment outside permitted initialization contexts; nameof supplies the parameter name.
Expected output (reasoned, not executed):
Rejected0using System;Console.WriteLine(new Bin().GetQuantity());Console.WriteLine(new Bin(7).GetQuantity());class Bin{ private readonly int quantity; public Bin() : this(0) { } public Bin(int quantity) { if (quantity < 0) throw new ArgumentOutOfRangeException(nameof(quantity)); this.quantity = quantity; } public int GetQuantity() => quantity;}The parameterless overload delegates to the validated constructor. Both paths use the same initialization rule.
Expected output (reasoned, not executed):
07Common mistake and correction
Do not write public void Bin(int quantity) as a constructor: constructors have no return type, and an ordinary member cannot share its containing type’s name. Also avoid validating only one constructor while letting another bypass the invariant.
Try it yourself
Design a Capacity class storing a readonly integer from 1 to 100. Provide constructors accepting an integer or defaulting to 10 through chaining. Use a getter method. Check default, 1, 100, 0 and 101; catch only the expected range exception for the last two.
Next: Properties, fields and access control. Examples target C# 14 / net10.0. They are static study material; compiler and ByteMind execution have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Constructors and invariants — knowledge check
Apply the lesson concepts to the following scenarios.
Which declaration is a constructor for class Bin?
What happens to the implicit parameterless constructor after declaring only Bin(int n)?
What does this.quantity = quantity assign?
Why use Bin() : this(0)?
What should happen for a negative initial quantity under the lesson contract?