C# Interview Question #14

What is encapsulation in C#?

OOP & Core C# Concepts Junior Beginner

Quick Interview Answer

Encapsulation means protecting an object's internal state and exposing only the operations that external code should use.

Detailed Explanation

Encapsulation means protecting an object's internal state and exposing only the operations that external code should use.

It is commonly implemented through access modifiers, properties, and methods. Instead of allowing callers to directly change sensitive fields, a class can validate changes through public methods.

This reduces invalid state and keeps implementation details inside the class.

Code Example

public class BankAccount
{
    private decimal _balance;

    public decimal Balance => _balance;

    public void Deposit(decimal amount)
    {
        if (amount <= 0)
            throw new ArgumentException("Amount must be greater than zero.");

        _balance += amount;
    }
}