Advertisement
Intermediate C# Lesson 3 of 10

Lesson 3: Constructors & Object Creation in C#

Every time you create an object with the new keyword, a constructor runs. Constructors are special methods that initialize objects, setting up initial state and validating parameters. This lesson covers how to write and use them effectively.

Advertisement

What Is a Constructor?

A constructor is a special method that runs when an object is created. It has the same name as the class, no return type, and can take parameters. Use constructors to set up required state and validate inputs.

Default Constructor (Parameterless)

public class Dog
{
    public string Name { get; set; }
    public int Age { get; set; }

    // Default constructor — no parameters
    public Dog()
    {
        Name = "Unknown";
        Age = 0;
    }
}

// Usage
var dog = new Dog();
Console.WriteLine($"{dog.Name}, {dog.Age}"); // Output: Unknown, 0

The compiler provides a default parameterless constructor automatically if you don't define any constructors. But it's often good to explicitly define one to set meaningful defaults.

Parameterized Constructors

Constructors can accept parameters to initialize fields with specific values:

public class Dog
{
    public string Name { get; set; }
    public int Age { get; set; }

    // Parameterized constructor
    public Dog(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

// Usage
var dog1 = new Dog("Buddy", 5);
var dog2 = new Dog("Max", 3);
Console.WriteLine($"{dog1.Name} is {dog1.Age} years old"); // Output: Buddy is 5 years old

Constructor Overloading

Like methods, constructors can be overloaded — multiple constructors with different parameters:

public class Rectangle
{
    public int Width { get; set; }
    public int Height { get; set; }

    // Default constructor
    public Rectangle()
    {
        Width = 1;
        Height = 1;
    }

    // Constructor with width and height
    public Rectangle(int width, int height)
    {
        Width = width;
        Height = height;
    }

    // Constructor for square
    public Rectangle(int size)
    {
        Width = size;
        Height = size;
    }
}

// Usage
var rect1 = new Rectangle();          // 1 x 1
var rect2 = new Rectangle(5, 10);     // 5 x 10
var square = new Rectangle(7);        // 7 x 7

Constructor Chaining with this()

To avoid duplication, one constructor can call another using this():

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    public int Year { get; set; }

    public Book() : this("Unknown", "Anonymous", 2025)
    {
    }

    public Book(string title, string author) : this(title, author, 2025)
    {
    }

    public Book(string title, string author, int year)
    {
        Title = title;
        Author = author;
        Year = year;
    }
}

// Usage
var book1 = new Book();
var book2 = new Book("C# Guide", "John Doe");
var book3 = new Book("C# Guide", "John Doe", 2024);

💡 Tip: Use constructor chaining to reduce code duplication and ensure all validation/initialization happens in one place.

Validation in Constructors

Constructors are the perfect place to validate inputs and enforce business rules:

public class BankAccount
{
    public string AccountNumber { get; set; }
    public decimal Balance { get; private set; }

    public BankAccount(string accountNumber, decimal initialBalance)
    {
        if (string.IsNullOrWhiteSpace(accountNumber))
            throw new ArgumentException("Account number cannot be empty");

        if (initialBalance < 0)
            throw new ArgumentException("Initial balance cannot be negative");

        AccountNumber = accountNumber;
        Balance = initialBalance;
    }
}

// Usage
try
{
    var account = new BankAccount("", 1000);  // Throws exception
}
catch (ArgumentException ex)
{
    Console.WriteLine(ex.Message); // Output: Account number cannot be empty
}

Field Initialization vs Constructor

You can initialize fields inline or in the constructor. Constructor initialization overrides inline defaults:

public class Player
{
    public string Name { get; set; } = "Guest";      // Default
    public int Level { get; set; } = 1;              // Default
    public List Inventory { get; set; } = new();

    public Player(string name, int level)
    {
        Name = name;          // Overrides default "Guest"
        Level = level;        // Overrides default 1
        // Inventory keeps its default initialization
    }
}

var player = new Player("Alice", 10);
Console.WriteLine($"{player.Name}, Level {player.Level}"); // Alice, Level 10
Advertisement

🧠 Quick Check — Lesson 3

What happens when you define a constructor with parameters in a class?

Lesson Summary

Constructors are special methods that initialize objects when created with new.

A default constructor takes no parameters; parameterized constructors initialize with specific values.

Constructor overloading lets you provide multiple ways to construct an object.

Use this() to chain constructors and avoid code duplication.

Validate inputs in constructors using throw new ArgumentException() to enforce business rules early.

Up Next

Lesson 4: Encapsulation & Access Modifiers

Next Lesson →