Encapsulation, Access Modifiers & Records Masterclass
Welcome to Phase 6 (Chapter 16): C# Encapsulation, Access Modifiers & Records Masterclass! Encapsulation hides internal implementation details and protects state from unauthorized external modification. In this lesson, we cover access modifiers (public, private, protected, internal), property validation, immutable objects, and C# 9+ Record types.
Access modifiers restrict the visibility of class members across projects and assemblies:
| Modifier | Accessibility Scope |
|---|---|
public | Accessible from any code anywhere in any project |
private | Accessible ONLY inside the defining class or struct |
protected | Accessible inside the defining class AND derived child classes |
internal | Accessible from any code within the SAME assembly (.dll / .exe) |
class BankAccount
{
private decimal balance; // Hidden private field
public decimal Balance
{
get => balance;
private set => balance = value; // Private setter
}
public void Deposit(decimal amount)
{
if (amount <= 0)
throw new ArgumentException("Deposit amount must be positive!");
balance += amount;
}
}
BankAccount acc = new BankAccount();
acc.Deposit(500);
Console.WriteLine($"Account Balance: {acc.Balance:C}");
Records are immutable reference types that automatically generate value-based equality methods, positional constructors, and support non-destructive mutation via the with expression:
// Record: Immutable reference type with built-in value equality!
public record Person(string FirstName, string LastName, int Age);
Person p1 = new("Ravi", "Kumar", 21);
Person p2 = new("Ravi", "Kumar", 21);
Console.WriteLine($"p1 == p2: {p1 == p2}"); // True (Value equality!)
Person p3 = p1 with { Age = 22 }; // Non-destructive mutation
Console.WriteLine($"p3: {p3}");
Q1: What is the main difference between a class and a record in C#?
Classes use reference-based equality (two instances are equal only if they refer to the same object in memory). Records use value-based equality and provide built-in immutability features.