Encapsulation, Access Modifiers & Records Masterclass

โšก C# 12 & .NET 8 ๐ŸŸข Chapter 16 of 35 ๐Ÿ“‚ Phase 6: Methods & OOP ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter: Encapsulation ยท Access Modifiers (public/private/protected/internal) ยท Property Validation ยท Immutable Objects ยท Record Types ยท Value Equality

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.

1Access Modifiers & Encapsulation

Access modifiers restrict the visibility of class members across projects and assemblies:

ModifierAccessibility Scope
publicAccessible from any code anywhere in any project
privateAccessible ONLY inside the defining class or struct
protectedAccessible inside the defining class AND derived child classes
internalAccessible from any code within the SAME assembly (.dll / .exe)
C# โ€” Encapsulation & Property Validation โ–ถ Run in Compiler
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}");
2C# 9+ Record Types

Records are immutable reference types that automatically generate value-based equality methods, positional constructors, and support non-destructive mutation via the with expression:

C# โ€” Record Types โ–ถ Run in Compiler
// 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}");
3Technical FAQs

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.