Constructors and Basic Encapsulation in C#

As you build more advanced classes in C#, you’ll need a way to automatically initialise objects with default or custom values — that’s where constructors come in. Alongside that, good class design means protecting your data from misuse, which we do using encapsulation.

Here we cover how to use constructors to set up objects and apply encapsulation to keep your classes clean, safe, and easy to maintain.


🏗️ What Is a Constructor?

A constructor is a special method that runs automatically when you create a new object. It’s used to initialise fields or properties when the object is first created.

🔹 Basic Constructor Example

public class Person
{
    public string Name;
    public int Age;

    // Constructor
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public void Greet()
    {
        Console.WriteLine($"Hello, I’m {Name} and I’m {Age} years old.");
    }
}

🔸 Using the Constructor

Person p = new Person("Alice", 30);
p.Greet(); // Output: Hello, I’m Alice and I’m 30 years old.

💡 The constructor has the same name as the class and no return type.


⚙️ Default Constructor

If you don’t define any constructor, C# adds a default constructor automatically:

Person p = new Person(); // Only works if no custom constructors exist

If you create your own constructor, and still want to allow a parameterless option, you must define it manually:

public Person() { }

🔐 What Is Encapsulation?

Encapsulation is the practice of keeping fields private and only exposing them through public properties or methods. It protects your data from being misused and lets you control how it’s accessed or changed.


🛡️ Encapsulation Example

public class BankAccount
{
    private decimal balance;

    public BankAccount(decimal initialBalance)
    {
        if (initialBalance >= 0)
            balance = initialBalance;
    }

    public decimal Balance
    {
        get { return balance; }
        private set
        {
            if (value >= 0)
                balance = value;
        }
    }

    public void Deposit(decimal amount)
    {
        if (amount > 0)
            Balance += amount;
    }

    public bool Withdraw(decimal amount)
    {
        if (amount > 0 && amount <= balance)
        {
            Balance -= amount;
            return true;
        }
        return false;
    }
}

This class:

  • Keeps balance private
  • Controls access via a property and methods
  • Prevents invalid changes

🧠 Why Encapsulation Matters

✅ Prevents objects from being put into an invalid state
✅ Makes your code easier to maintain and debug
✅ Protects sensitive data and improves security
✅ Encourages better program design


🧪 Practice Exercise

Create a Product class with:

  • A private field price
  • A property Price that can’t be negative
  • A constructor that accepts a name and price
  • A method ShowInfo() that displays the name and price
public class Product
{
    private decimal price;

    public string Name { get; set; }

    public decimal Price
    {
        get { return price; }
        set
        {
            if (value >= 0)
                price = value;
        }
    }

    public Product(string name, decimal price)
    {
        Name = name;
        Price = price;
    }

    public void ShowInfo()
    {
        Console.WriteLine($"Product: {Name}, Price: £{Price}");
    }
}

📚 Summary

ConceptPurpose
ConstructorSets up new objects with initial values
EncapsulationProtects data using private fields
PropertyPublic access point with validation logic

📬 Want help applying encapsulation or building real-world constructors in your own app? Get in touch — we’re here to guide you through professional C# coding techniques, step by step.