Encapsulation in .NET
Introduction
🔐 Introduction
In object-oriented programming (OOP), especially in .NET, encapsulation is a key principle that helps you build secure, organized, and maintainable applications.
In simple terms, encapsulation means:
- Wrapping data and methods into a single unit (class)
- Restricting direct access to internal components
This protects the internal state and enforces controlled access.
🏧 Encapsulation in Real Life: The ATM Analogy
Think of an ATM machine:
- You interact with buttons/touchscreen
- You can't access internal circuits or logic
- You get limited access: card, PIN, withdraw money
This is encapsulation — the interface is exposed, internals are hidden.
💡 How .NET Implements Encapsulation
- Using classes and objects
- Using access modifiers:
private,public, etc. - Using properties (getters/setters) for controlled access
🏦 Example: Bank Account
class BankAccount {
private decimal balance;
public string AccountHolder { get; set; }
public void Deposit(decimal amount) {
if (amount > 0)
balance += amount;
}
public void Withdraw(decimal amount) {
if (amount > 0 && amount <= balance)
balance -= amount;
}
public decimal GetBalance() {
return balance;
}
}
Explanation:
The balance field is private and protected from outside access.
The Deposit and Withdraw methods offer controlled modification.
The GetBalance method allows read-only access.
💼 Why Encapsulation Matters
- Data Protection: Avoid unwanted or invalid changes
- Controlled Access: Use getters/setters for safe updates
- Maintainability: Change internal logic without affecting external code
- Testability: Encapsulated modules are easier to test
✅ Best Practices
- Use
privatefields for sensitive data - Use
publicproperties with validation logic - Use
private setor read-only properties where needed - Prefer composition over inheritance for complex encapsulation
🔒 Read-Only Property Example
class Product {
public string Name { get; set; }
public decimal Price { get; private set; }
public Product(string name, decimal price) {
Name = name;
Price = price;
}
}
Explanation: Price can only be set from inside the class, not modified externally.
🧩 Encapsulation vs Abstraction
| Feature | Encapsulation | Abstraction |
|---|---|---|
| Focus | Hides internal data | Hides implementation logic |
| Main Tool | Access Modifiers | Abstract classes, Interfaces |
| Purpose | Protect internal state | Simplify usage |
| Example | Private balance in BankAccount | Abstract GetArea() in Shape |
📌 Conclusion
Encapsulation is essential for secure and maintainable .NET applications. By protecting internal data and exposing only what's necessary, you create clean and modular code.
Next: Learn about Polymorphism in .NET or Abstraction Techniques.
Comments
Post a Comment