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:
csharp1class Person2{3 public string Name;4 public int Age;5}67// Default constructor creates object with default values8Person 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:
csharp1class Person2{3 public string Name;4 public int Age;56 // Constructor7 public Person()8 {9 Name = "Unknown";10 Age = 0;11 Console.WriteLine("Person created!");12 }13}1415Person p = new Person(); // Prints "Person created!"16Console.WriteLine(p.Name); // "Unknown"
Parameterized Constructor
Accept parameters to initialize the object:
csharp1class Person2{3 public string Name;4 public int Age;56 public Person(string name, int age)7 {8 Name = name;9 Age = age;10 }11}1213Person p = new Person("Alice", 25);14Console.WriteLine($"{p.Name}, {p.Age}"); // Alice, 25
The this Keyword
Use this to refer to the current instance:
csharp1class Person2{3 public string Name;4 public int Age;56 public Person(string name, int age)7 {8 this.Name = name; // 'this' clarifies we mean the field9 this.Age = age;10 }11}
When parameter names match field names, this distinguishes them:
csharp1class Rectangle2{3 public double Width;4 public double Height;56 public Rectangle(double width, double height)7 {8 this.Width = width; // this.Width is the field9 this.Height = height; // width is the parameter10 }11}
Multiple Constructors (Overloading)
Classes can have multiple constructors:
csharp1class Person2{3 public string Name;4 public int Age;56 // Default constructor7 public Person()8 {9 Name = "Unknown";10 Age = 0;11 }1213 // Constructor with name only14 public Person(string name)15 {16 Name = name;17 Age = 0;18 }1920 // Constructor with both21 public Person(string name, int age)22 {23 Name = name;24 Age = age;25 }26}2728// All three ways to create a Person29Person p1 = new Person();30Person p2 = new Person("Alice");31Person p3 = new Person("Bob", 30);
Constructor Chaining
One constructor can call another using this:
csharp1class Person2{3 public string Name;4 public int Age;56 public Person() : this("Unknown", 0)7 {8 // Calls the two-parameter constructor9 }1011 public Person(string name) : this(name, 0)12 {13 // Calls the two-parameter constructor14 }1516 public Person(string name, int age)17 {18 Name = name;19 Age = age;20 Console.WriteLine($"Created: {Name}, {Age}");21 }22}2324Person p1 = new Person(); // Created: Unknown, 025Person p2 = new Person("Alice"); // Created: Alice, 026Person p3 = new Person("Bob", 25); // Created: Bob, 25
Constructors with Properties
csharp1class Product2{3 public string Name { get; set; }4 public decimal Price { get; set; }5 public int Quantity { get; set; }67 public Product(string name, decimal price, int quantity = 0)8 {9 Name = name;10 Price = price;11 Quantity = quantity;12 }1314 public decimal TotalValue => Price * Quantity;15}1617Product p = new Product("Widget", 9.99m, 100);18Console.WriteLine($"{p.Name}: {p.TotalValue:C}");
Primary Constructors (C# 12+)
A concise syntax for simple constructors:
csharp1// Traditional2class Person3{4 public string Name { get; }5 public int Age { get; }67 public Person(string name, int age)8 {9 Name = name;10 Age = age;11 }12}1314// 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:
csharp1class BankAccount2{3 public string AccountNumber { get; }4 public decimal Balance { get; private set; }56 public BankAccount(string accountNumber, decimal initialDeposit)7 {8 if (string.IsNullOrWhiteSpace(accountNumber))9 throw new ArgumentException("Account number is required");1011 if (initialDeposit < 0)12 throw new ArgumentException("Initial deposit cannot be negative");1314 AccountNumber = accountNumber;15 Balance = initialDeposit;16 }17}1819// Valid20BankAccount account = new BankAccount("12345", 100);2122// Throws exception23// BankAccount bad = new BankAccount("", 100);
Read-Only Fields
Fields marked readonly can only be set in the constructor:
csharp1class Circle2{3 public readonly double Radius;45 public Circle(double radius)6 {7 Radius = radius; // OK in constructor8 }910 public void TryChange()11 {12 // Radius = 10; // Error! Cannot modify readonly13 }14}
Static Constructors
Initialize static (class-level) data:
csharp1class Counter2{3 public static int TotalCount { get; private set; }45 // Static constructor - runs once when class is first used6 static Counter()7 {8 TotalCount = 0;9 Console.WriteLine("Counter class initialized");10 }1112 public Counter()13 {14 TotalCount++;15 }16}1718Counter c1 = new Counter(); // Prints "Counter class initialized", TotalCount = 119Counter c2 = new Counter(); // TotalCount = 220Counter c3 = new Counter(); // TotalCount = 3
Practical Example
csharp1class Book2{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; }89 // Main constructor10 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");2021 Title = title;22 Author = author;23 Year = year;24 Pages = pages;25 ISBN = isbn ?? "";26 }2728 // Simplified constructor29 public Book(string title, string author) : this(title, author, DateTime.Now.Year, 1, "")30 {31 }3233 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}4142Book book1 = new Book("1984", "George Orwell", 1949, 328, "978-0451524935");43book1.Display();4445Book 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
thisrefers to the current instance- Overload constructors for different initialization options
- Chain constructors with
this(...)to avoid duplication - Validate inputs in constructors
readonlyfields can only be set in constructors
Next, we'll explore methods within classes.