C# Tutorial · Object-Oriented C# · Lesson 12 of 22

C# Classes and Objects

Classes, constructors, fields, properties and methods.

Classes and properties

A class bundles data and behaviour. Properties ({ get; set; }) expose data with optional validation; init makes a property settable only during creation:

Example 1
var acct = new BankAccount("Ada");
acct.Deposit(100);
acct.Withdraw(30);
Console.WriteLine($"{acct.Owner}: {acct.Balance}");
try { acct.Withdraw(500); }
catch (InvalidOperationException e) { Console.WriteLine($"Rejected: {e.Message}"); }

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

    public BankAccount(string owner) => Owner = owner;

    public void Deposit(decimal amount)
    {
        if (amount <= 0) throw new ArgumentOutOfRangeException(nameof(amount));
        Balance += amount;
    }

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

Output

Ada: 70
Rejected: Insufficient funds

Run this on your computer — see “Get Started” for setup.

Primary constructors (C# 12)

Parameters on the class declaration are available throughout the class:

Example 2
var p = new Product("Mug", 9.5m) { Tags = ["kitchen", "gift"] };
Console.WriteLine(p.Label());
Console.WriteLine(p.Tags.Count);

class Product(string name, decimal price)
{
    public string Name { get; } = name;
    public List<string> Tags { get; init; } = [];
    public string Label() => $"{Name} — ${price:0.00}";
}

Output

Mug — $9.50
2

Run this on your computer — see “Get Started” for setup.

Test yourself

What does { get; private set; } mean?

  1. Read-only everywhere
  2. Anyone can read it, only the class can change it
  3. Write-only
  4. Private to read and write
Show answer

Answer: Anyone can read it, only the class can change it