Access Modifiers & Encapsulation
Learn public, private, protected, and internal access modifiers, and the principle of encapsulation.
What is Encapsulation?
Encapsulation means bundling data and the methods that operate on it inside a class, while restricting direct access to that data from outside. It protects an object from being put into an invalid state.
Access Modifiers
| Modifier | Accessible From |
|---|---|
| public | Anywhere |
| private | Only inside the same class (the default if unspecified) |
| protected | The same class and any derived (child) classes |
| internal | Anywhere within the same project/assembly |
Encapsulation in Practice
class BankAccount{ private decimal balance; // hidden from outside
public void Deposit(decimal amount) { if (amount <= 0) throw new ArgumentException("Amount must be positive."); balance += amount; }
public decimal GetBalance() => balance;}
var account = new BankAccount();account.Deposit(100);Console.WriteLine(account.GetBalance());// account.balance = -500; // Error: balance is private, can't be set directlyOutput
Click Run to see what this code prints.
Why Hide the Field?
By keeping `balance` private and only exposing `Deposit()`, the class guarantees the balance can never become invalid — every change goes through validated logic.
FAQs
For class members it's `private`; for the class itself it's `internal`.
Summary
- Encapsulation hides internal state and exposes controlled access.
- public, private, protected, and internal control visibility.
- Keeping fields private and validating through methods prevents invalid object states.