LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 2318 min read

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

ModifierAccessible From
publicAnywhere
privateOnly inside the same class (the default if unspecified)
protectedThe same class and any derived (child) classes
internalAnywhere 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 directly
Output

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.
Next Lesson →

Inheritance