10 minlesson

Constructors

Constructors

A constructor is a special method that runs when an object is created. It's used to initialize the object with valid starting values.

Default Constructor

If you don't define a constructor, C# provides a default one:

csharp
1class Person
2{
3 public string Name;
4 public int Age;
5}
6
7// Default constructor creates object with default values
8Person p = new Person();
9// p.Name is null, p.Age is 0

Defining a Constructor

A constructor has the same name as the class and no return type:

csharp
1class Person
2{
3 public string Name;
4 public int Age;
5
6 // Constructor
7 public Person()
8 {
9 Name = "Unknown";
10 Age = 0;
11 Console.WriteLine("Person created!");
12 }
13}
14
15Person p = new Person(); // Prints "Person created!"
16Console.WriteLine(p.Name); // "Unknown"

Parameterized Constructor

Accept parameters to initialize the object:

csharp
1class Person
2{
3 public string Name;
4 public int Age;
5
6 public Person(string name, int age)
7 {
8 Name = name;
9 Age = age;
10 }
11}
12
13Person p = new Person("Alice", 25);
14Console.WriteLine($"{p.Name}, {p.Age}"); // Alice, 25

The this Keyword

Use this to refer to the current instance:

csharp
1class Person
2{
3 public string Name;
4 public int Age;
5
6 public Person(string name, int age)
7 {
8 this.Name = name; // 'this' clarifies we mean the field
9 this.Age = age;
10 }
11}

When parameter names match field names, this distinguishes them:

csharp
1class Rectangle
2{
3 public double Width;
4 public double Height;
5
6 public Rectangle(double width, double height)
7 {
8 this.Width = width; // this.Width is the field
9 this.Height = height; // width is the parameter
10 }
11}

Multiple Constructors (Overloading)

Classes can have multiple constructors:

csharp
1class Person
2{
3 public string Name;
4 public int Age;
5
6 // Default constructor
7 public Person()
8 {
9 Name = "Unknown";
10 Age = 0;
11 }
12
13 // Constructor with name only
14 public Person(string name)
15 {
16 Name = name;
17 Age = 0;
18 }
19
20 // Constructor with both
21 public Person(string name, int age)
22 {
23 Name = name;
24 Age = age;
25 }
26}
27
28// All three ways to create a Person
29Person p1 = new Person();
30Person p2 = new Person("Alice");
31Person p3 = new Person("Bob", 30);

Constructor Chaining

One constructor can call another using this:

csharp
1class Person
2{
3 public string Name;
4 public int Age;
5
6 public Person() : this("Unknown", 0)
7 {
8 // Calls the two-parameter constructor
9 }
10
11 public Person(string name) : this(name, 0)
12 {
13 // Calls the two-parameter constructor
14 }
15
16 public Person(string name, int age)
17 {
18 Name = name;
19 Age = age;
20 Console.WriteLine($"Created: {Name}, {Age}");
21 }
22}
23
24Person p1 = new Person(); // Created: Unknown, 0
25Person p2 = new Person("Alice"); // Created: Alice, 0
26Person p3 = new Person("Bob", 25); // Created: Bob, 25

Constructors with Properties

csharp
1class Product
2{
3 public string Name { get; set; }
4 public decimal Price { get; set; }
5 public int Quantity { get; set; }
6
7 public Product(string name, decimal price, int quantity = 0)
8 {
9 Name = name;
10 Price = price;
11 Quantity = quantity;
12 }
13
14 public decimal TotalValue => Price * Quantity;
15}
16
17Product p = new Product("Widget", 9.99m, 100);
18Console.WriteLine($"{p.Name}: {p.TotalValue:C}");

Primary Constructors (C# 12+)

A concise syntax for simple constructors:

csharp
1// Traditional
2class Person
3{
4 public string Name { get; }
5 public int Age { get; }
6
7 public Person(string name, int age)
8 {
9 Name = name;
10 Age = age;
11 }
12}
13
14// Primary constructor (C# 12+)
15class Person(string name, int age)
16{
17 public string Name { get; } = name;
18 public int Age { get; } = age;
19}

Validation in Constructors

Ensure objects start in a valid state:

csharp
1class BankAccount
2{
3 public string AccountNumber { get; }
4 public decimal Balance { get; private set; }
5
6 public BankAccount(string accountNumber, decimal initialDeposit)
7 {
8 if (string.IsNullOrWhiteSpace(accountNumber))
9 throw new ArgumentException("Account number is required");
10
11 if (initialDeposit < 0)
12 throw new ArgumentException("Initial deposit cannot be negative");
13
14 AccountNumber = accountNumber;
15 Balance = initialDeposit;
16 }
17}
18
19// Valid
20BankAccount account = new BankAccount("12345", 100);
21
22// Throws exception
23// BankAccount bad = new BankAccount("", 100);

Read-Only Fields

Fields marked readonly can only be set in the constructor:

csharp
1class Circle
2{
3 public readonly double Radius;
4
5 public Circle(double radius)
6 {
7 Radius = radius; // OK in constructor
8 }
9
10 public void TryChange()
11 {
12 // Radius = 10; // Error! Cannot modify readonly
13 }
14}

Static Constructors

Initialize static (class-level) data:

csharp
1class Counter
2{
3 public static int TotalCount { get; private set; }
4
5 // Static constructor - runs once when class is first used
6 static Counter()
7 {
8 TotalCount = 0;
9 Console.WriteLine("Counter class initialized");
10 }
11
12 public Counter()
13 {
14 TotalCount++;
15 }
16}
17
18Counter c1 = new Counter(); // Prints "Counter class initialized", TotalCount = 1
19Counter c2 = new Counter(); // TotalCount = 2
20Counter c3 = new Counter(); // TotalCount = 3

Practical Example

csharp
1class Book
2{
3 public string Title { get; }
4 public string Author { get; }
5 public int Year { get; }
6 public int Pages { get; }
7 public string ISBN { get; }
8
9 // Main constructor
10 public Book(string title, string author, int year, int pages, string isbn)
11 {
12 if (string.IsNullOrWhiteSpace(title))
13 throw new ArgumentException("Title is required");
14 if (string.IsNullOrWhiteSpace(author))
15 throw new ArgumentException("Author is required");
16 if (year < 1450 || year > DateTime.Now.Year)
17 throw new ArgumentException("Invalid year");
18 if (pages < 1)
19 throw new ArgumentException("Pages must be positive");
20
21 Title = title;
22 Author = author;
23 Year = year;
24 Pages = pages;
25 ISBN = isbn ?? "";
26 }
27
28 // Simplified constructor
29 public Book(string title, string author) : this(title, author, DateTime.Now.Year, 1, "")
30 {
31 }
32
33 public void Display()
34 {
35 Console.WriteLine($"\"{Title}\" by {Author} ({Year})");
36 Console.WriteLine($"Pages: {Pages}");
37 if (!string.IsNullOrEmpty(ISBN))
38 Console.WriteLine($"ISBN: {ISBN}");
39 }
40}
41
42Book book1 = new Book("1984", "George Orwell", 1949, 328, "978-0451524935");
43book1.Display();
44
45Book book2 = new Book("My New Book", "Jane Doe");
46book2.Display();

Summary

In this lesson, you learned:

  • Constructors initialize objects when created
  • Constructors have the same name as the class
  • Use parameters to accept initial values
  • this refers to the current instance
  • Overload constructors for different initialization options
  • Chain constructors with this(...) to avoid duplication
  • Validate inputs in constructors
  • readonly fields can only be set in constructors

Next, we'll explore methods within classes.