Lesson 13 — Object Initialisation
Constructors
C# constructors initialise objects. Constructor chaining with this(), base(), primary constructors (C# 12), and records reduce boilerplate.
CSHARP — Constructor chaining
public class Learner {
public string Name { get; }
public int Age { get; }
public string Course { get; }
public double Mark { get; private set; }
// Full constructor:
public Learner(string name, int age, string course, double mark) {
Name = name;
Age = age;
Course = course;
Mark = mark;
}
// Overload — delegates to full constructor:
public Learner(string name, int age, string course)
: this(name, age, course, 0.0) { }
// Minimal constructor:
public Learner(string name) : this(name, 0, "Undecided") { }
public void Introduce() =>
Console.WriteLine($"I am {Name}, studying {Course}. Mark: {Mark}%");
}
var l1 = new Learner("Thandi", 21, "C#", 74.5);
var l2 = new Learner("Sipho", 24, "Java");
var l3 = new Learner("Lerato");
l1.Introduce(); l2.Introduce(); l3.Introduce();
Primary Constructors (C# 12)
CSHARP — Primary constructors
// Primary constructor — parameters available throughout the class body:
public class Learner(string name, int age, string course) {
public string Name => name;
public int Age => age;
public string Course => course;
public void Introduce() =>
Console.WriteLine($"I am {name}, aged {age}, studying {course}.");
}
// Records are even more concise:
record LearnerRecord(string Name, int Age, string Course, double Mark);
var r = new LearnerRecord("Bongani", 22, "SQL", 88.5);
Console.WriteLine(r); // LearnerRecord { Name = Bongani, ... }
Static Constructors
CSHARP — Static constructor
public class Database {
public static readonly string ConnectionString;
// Static constructor — runs once when the class is first used:
static Database() {
ConnectionString = Environment.GetEnvironmentVariable("DB_CONN")
?? "Server=localhost;Database=your-it-tutor;";
Console.WriteLine("Database class initialised.");
}
}
Practice Task
Your Turn
Write a BankAccount class with: a full constructor taking accountNumber (final/readonly), holderName, and initialBalance; an overload taking only holderName and generating an accountNumber using a static counter; validation in the full constructor (balance >= 0). Show constructor chaining with : this().
Common Mistakes
- Adding a return type to a constructor — makes it a regular method.
- Not using
this()delegation — copy-pasted constructor code breaks the DRY principle. this()must be the first thing called — no code before it.- Records are immutable by default — use
withto create modified copies.
Professional Tip
Constructor chaining keeps all initialisation logic in one place. The minimal constructors delegate to the full one — no duplicated validation code.
Mini Quiz
What does : this(...) do in a C# constructor?
: this(...) delegates to another constructor in the same class. : base(...) calls the parent class constructor.