9. Classes and Objects

A class is a blueprint; an object is an instance of it, created with new. A class groups data and behaviour: fields (variables stored in the object), properties (controlled access to data with get and set), constructors (code that sets up a new object), methods (behaviour), indexers and events. Static members belong to the class itself and are shared by all objects, while instance members belong to each object. The keyword this refers to the current object.

Encapsulation means keeping data private and exposing only what is needed. Access modifiers control visibility: public (anywhere), private (inside the class only, the default for members), protected (the class and its subclasses), internal (the same project/assembly), plus protected internal and private protected. Auto-properties ({ get; set; }) remove boilerplate, a private set or init accessor makes a property read-only to outsiders, and a property with a body can validate values before storing them in a private backing field.

Constructors can be overloaded and can call each other with : this(...). Object initializers (new Student { Name = "Zodwa" }) set properties on creation, and required members force callers to set them. Other building blocks: const and readonly fields, static classes and extension methods, structs (value types, copied on assignment), records (concise immutable data types with value equality and the with expression), enums, and partial classes that split one class across files. Override ToString to control how an object prints.

Key points to remember

  • Class = reference type: assigning a variable copies the reference, so both variables refer to the same object. Struct = value type: assigning copies the data.
  • Make fields private and expose data through properties; put validation in the property setter or a method.
  • A class with no constructor gets a default parameterless one. As soon as you write any constructor, the default is no longer generated.
  • Use const for compile-time constants (const double Pi) and static readonly for values computed once at run time. readonly instance fields can be set only in the constructor.
  • Static members are called through the class name (Account.Count). A static class cannot be instantiated and holds only static members (utility helpers).
  • Records compare by value: two records with the same data are equal with ==. Classes compare by reference unless you override Equals.
  • Common mistake: NullReferenceException from using an object that is null. Initialise objects, use ?. and check for null.
  • Use the nullable annotations: string? may be null, string should not be.
  • Each class should have one clear responsibility (a Customer holds customer data; a CustomerRepository saves it).

Example 1: A simple class

C#
var p = new Person("Lerato", 29);
p.Birthday();
Console.WriteLine(p);

class Person
{
    public string Name { get; set; }
    public int Age { get; private set; }

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

    public void Birthday() => Age++;
    public override string ToString() => $"{Name} ({Age})";
}
Show output Output
Lerato (30)

Example 2: Fields, constants, readonly and static members

C#
var a = new Account("Ann");
var b = new Account("Ben");
Console.WriteLine(Account.Count);          // shared by all accounts
Console.WriteLine(Account.BankName);
Console.WriteLine(a.Owner + " " + b.Number);

class Account
{
    public const string BankName = "Cape Bank";      // compile-time constant
    public static int Count;                         // one copy for the class
    public readonly string Owner;                    // set once, in the constructor
    public int Number { get; }

    public Account(string owner)
    {
        Owner = owner;
        Count++;
        Number = Count;
    }
}
Show output Output
2
Cape Bank
Ann 2

Example 3: Properties: validation and computed values

C#
var item = new Product { Name = "Pen", Price = 12.5m };
Console.WriteLine($"{item.Name}: {item.PriceWithVat}");

try { item.Price = -5m; }
catch (ArgumentException ex) { Console.WriteLine(ex.Message); }

class Product
{
    private decimal _price;                       // backing field
    public string Name { get; set; } = "";

    public decimal Price
    {
        get => _price;
        set
        {
            if (value < 0) throw new ArgumentException("Price cannot be negative");
            _price = value;
        }
    }

    public decimal PriceWithVat => Price * 1.15m;  // read-only, calculated
}
Show output Output
Pen: 14.375
Price cannot be negative

Example 4: Constructors: overloading and chaining

C#
Console.WriteLine(new Rectangle().Area);
Console.WriteLine(new Rectangle(3).Area);
Console.WriteLine(new Rectangle(2, 5).Area);

class Rectangle
{
    public double Width { get; }
    public double Height { get; }

    public Rectangle() : this(1, 1) { }                   // calls the 2-parameter one
    public Rectangle(double side) : this(side, side) { }
    public Rectangle(double width, double height)
    {
        Width = width;
        Height = height;
    }

    public double Area => Width * Height;
}
Show output Output
1
9
10

Example 5: Encapsulation with access modifiers

C#
var acc = new BankAccount();
acc.Deposit(500);
acc.Withdraw(120);
Console.WriteLine(acc.Balance);
// acc.Balance = 1000;          // error: the setter is private

try { acc.Withdraw(1000); }
catch (InvalidOperationException ex) { Console.WriteLine(ex.Message); }

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

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

    public void Withdraw(decimal amount)
    {
        if (amount > Balance) throw new InvalidOperationException("Insufficient funds");
        Balance -= amount;
    }
}
Show output Output
380
Insufficient funds

Example 6: Object initializers, required and init

C#
var s = new Student { Name = "Zodwa", Grade = 11 };
Console.WriteLine($"{s.Name} - Grade {s.Grade}");
// s.Name = "Other";            // error: init-only after creation
// var bad = new Student();     // error: Name is required

class Student
{
    public required string Name { get; init; }
    public int Grade { get; set; }
}
Show output Output
Zodwa - Grade 11

Example 7: Class vs struct

C#
Point2 p1 = new Point2(1, 2);
Point2 p2 = p1;                // struct: a copy
p2.X = 9;
Console.WriteLine(p1.X);

Box b1 = new Box { X = 1 };
Box b2 = b1;                   // class: same object
b2.X = 9;
Console.WriteLine(b1.X);

struct Point2
{
    public int X, Y;
    public Point2(int x, int y) { X = x; Y = y; }
}
class Box
{
    public int X;
}
Show output Output
1
9

Example 8: Records

C#
var a = new Point(1, 2);
var b = a with { X = 5 };          // copy with one change
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(a == new Point(1, 2));    // value equality
var (x, y) = b;                              // deconstruct
Console.WriteLine(x + y);

record Point(int X, int Y);
Show output Output
Point { X = 1, Y = 2 }
Point { X = 5, Y = 2 }
True
7

Example 9: Indexers and operator overloading

C#
var week = new Week();
Console.WriteLine(week[1]);

var v = new Vector(1, 2) + new Vector(3, 4);
Console.WriteLine(v);

class Week
{
    private readonly string[] _days = { "Mon", "Tue", "Wed" };
    public string this[int index] => _days[index];       // indexer
}

class Vector
{
    public int X { get; }
    public int Y { get; }
    public Vector(int x, int y) { X = x; Y = y; }
    public static Vector operator +(Vector a, Vector b) => new(a.X + b.X, a.Y + b.Y);
    public override string ToString() => $"({X}, {Y})";
}
Show output Output
Tue
(4, 6)

Example 10: Static classes and extension methods

C#
Console.WriteLine(MathHelper.Square(5));
Console.WriteLine("hello".Shout());
Console.WriteLine(new[] { 1, 2, 3, 4 }.SumOfSquares());

static class MathHelper
{
    public static int Square(int x) => x * x;
}

static class Extensions
{
    public static string Shout(this string s) => s.ToUpper() + "!";
    public static int SumOfSquares(this int[] numbers) => numbers.Sum(n => n * n);
}
Show output Output
25
HELLO!
30

Example 11: Overriding Equals and ToString

C#
var a = new Money(10, "ZAR");
var b = new Money(10, "ZAR");
Console.WriteLine(a == b);          // different objects
Console.WriteLine(a.Equals(b));     // same content
Console.WriteLine(a);

class Money
{
    public decimal Amount { get; }
    public string Currency { get; }
    public Money(decimal amount, string currency) { Amount = amount; Currency = currency; }

    public override bool Equals(object? obj) =>
        obj is Money m && m.Amount == Amount && m.Currency == Currency;
    public override int GetHashCode() => HashCode.Combine(Amount, Currency);
    public override string ToString() => $"{Amount} {Currency}";
}
Show output Output
False
True
10 ZAR