12
Lesson 12 of 35 ยท OOP

Classes & Objects

Classes are the fundamental building block of C#. A class bundles data (fields/properties) and behaviour (methods) together. This lesson covers class definition, constructors, properties, access modifiers, and C# 14 primary constructors.

Defining a Class

Use the class keyword. Fields store data; methods define behaviour. By convention, class names use PascalCase and file names match the class name.

Basic class BankAccount.cs
public class BankAccount
{
    private decimal _balance;
    public string Owner { get; }

    public BankAccount(string owner, decimal initialBalance)
    {
        Owner    = owner;
        _balance = initialBalance;
    }

    public void Deposit(decimal amount)
    {
        if (amount <= 0) throw new ArgumentException("Amount must be positive");
        _balance += amount;
    }

    public bool Withdraw(decimal amount)
    {
        if (amount > _balance) return false;
        _balance -= amount;
        return true;
    }

    public override string ToString()
        => $"Account[{Owner}]: {_balance:C2}";
}

Properties

Properties expose fields safely using get and set accessors. Auto-properties generate the backing field automatically. init accessors allow setting a value only during object initialisation.

Properties Props.cs
public class Person
{
    // Auto-property with init
    public string Name { get; init; } = string.Empty;
    public int Age  { get; set; }

    // Computed property
    public bool IsAdult => Age >= 18;
}

var p = new Person { Name = "Alice", Age = 22 };
Console.WriteLine(p.IsAdult); // True
// p.Name = "Bob"; // โ† compile error โ€” init-only

C# 14 Primary Constructors

C# 14 lets you declare constructor parameters directly on the class declaration. The parameters are in scope throughout the entire class body.

Primary constructor PrimaryCtorClass.cs
// C# 14 primary constructor โ€” no boilerplate
public class Customer(string name, string email)
{
    public string Name  { get; } = name;
    public string Email { get; } = email;

    public void Send(string message)
        => Console.WriteLine($"Emailing {Email}: {message}");
}

var c = new Customer("Alice", "[email protected]");
c.Send("Your order has shipped!");

Static Members

A static member belongs to the class itself, not to any instance. Access it through the class name, not an object reference.

Static members Static.cs
public class Counter
{
    public static int Total { get; private set; } = 0;
    public int Id { get; }

    public Counter()
    {
        Total++;
        Id = Total;
    }
}

var a = new Counter(); // Total = 1
var b = new Counter(); // Total = 2
Console.WriteLine(Counter.Total); // 2