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;
}
{
// 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
| Modifier | Accessible From |
|---|---|
public | Anywhere |
private | Same class only |
protected | Same class + subclasses |
internal | Same assembly (project) |
protected internal | Same assembly OR subclasses |
private protected | Same 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
}
{
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
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