OOP: Encapsulation & Access

🔷 C# Programming Lesson 9 Intermediate

Encapsulation hides the internal details of a class. C# provides five access modifiers to control visibility across namespaces and assemblies.

1 Access Modifiers & Backing Fields

C# access modifiers control visibility boundaries:

  • private: Restricts access strictly to the declaring class.
  • public: Open and accessible from any code file.
  • protected: Accessible within the class and by child subclasses.
  • internal: Accessible within the same compiled assembly file (project DLL).

When write custom validation logic in getters/setters, declare a private **backing field** explicitly to hold the value, preventing infinite recursion bugs.

2 Encapsulation Code

Let's run a program utilizing encapsulation and backing field validations:

C# — Encapsulation ▶ Run Code
using System;

class Account {
    private double _balance; // Private backing field

    // Public property with validation logic
    public double Balance {
        get { return _balance; }
        set {
            if (value >= 0) {
                _balance = value;
            } else {
                Console.WriteLine("Error: Negative balances are rejected!");
            }
        }
    }
}

class Program {
    static void Main() {
        Account acc = new Account();
        acc.Balance = 500.0; // Invokes setter
        Console.WriteLine("Balance: $" + acc.Balance); // Invokes getter

        acc.Balance = -200.0; // Rejects update
        Console.WriteLine("Balance remains: $" + acc.Balance);
    }
}
3 Code Challenge
Challenge: Write a class named `Employee` with a private field `salary`. Expose a property `Salary` with a setter validation that rejects salary updates below `1000`. Test this logic in `Main()`.