๐Ÿ  VisualStudioTutor.com  ยท  C# Tutorial Home  ยท  C# Lesson 5 of 40
Lesson 5 of 40 OOP Intermediate โฑ 35 min

Classes & Objects โ€” OOP Fundamentals

Build real-world models with classes, properties, constructors, access modifiers, static members, and understand how object references work in memory.

Part 1: Defining a Class

public class BankAccount
{
    // Auto-property with init-only setter
    public string Owner { get; init; }
    public decimal Balance { get; private set; }

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

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

Part 2: Access Modifiers

ModifierAccessible From
publicAnywhere
privateSame class only
protectedSame class + subclasses
internalSame assembly (project)
protected internalSame assembly OR subclasses
private protectedSame class + subclasses in same assembly

Part 3: Static Members & Singleton Pattern

public class AppConfig
{
    private static readonly AppConfig _instance = new();
    public static AppConfig Instance => _instance;

    public string ConnectionString { get; set; } = "";
    private AppConfig() {} // Private constructor
}

Part 4: Object Initializers & Records

// Object initializer (mutable)
var acc = new BankAccount("Alice", 1000m);

// Record (immutable, value equality)
public record Point(double X, double Y);
var p1 = new Point(1, 2);
var p2 = p1 with { X = 5 }; // Non-destructive mutation
Console.WriteLine(p1 == p2); // false

C# in Visual Studio 2026

๐Ÿ“˜ This lesson is part of the book C# in Visual Studio 2026 by Dr. Liew Voon Kiong.

View on Amazon Kindle Edition