Encapsulation

Encapsulation is one of the fundamental concepts of object-oriented programming (OOP) that refers to the practice of hiding the internal details of an object and exposing only the essential information or functionality through a well-defined public interface. Encapsulation allows you to protect the internal state of an object from being modified by external code, and provides a way to ensure that the object is always in a valid state.

In C#, encapsulation is achieved by using access modifiers on the class members. There are three access modifiers in C#: public, private, and protected. Here is a brief overview of each modifier:

Public: Public members are accessible from anywhere in the code, and can be called or modified by any other code that has access to the object.

Private: Private members are only accessible from within the same class, and cannot be accessed or modified from outside the class.

Protected: Protected members are accessible from within the same class and any derived classes. They cannot be accessed from outside the class or its derived classes.

To encapsulate the internal state of an object in C#, you can use private fields and public properties or methods to access and modify the state. Here's an example:
class BankAccount
{
    private decimal balance;

    public decimal Balance
    {
        get { return balance; }
        private set { balance = value; }
    }

    public void Deposit(decimal amount)
    {
        balance += amount;
    }

    public void Withdraw(decimal amount)
    {
        if (amount > balance)
        {
            throw new InvalidOperationException("Insufficient funds.");
        }
        balance -= amount;
    }
}

In this example, the BankAccount class has a private field balance that stores the current balance of the account. The public Balance property provides read-only access to the balance, and the Deposit and Withdraw methods are used to modify the balance.

By using encapsulation to hide the internal state of the BankAccount object, we can prevent other code from accessing or modifying the balance directly. This helps to ensure that the account is always in a valid state and makes it easier to maintain and extend the code over time.

Comments

Popular posts from this blog

OpenSolaris and Linux virtual memory and address space structures

Tagged architectures and multi-level UNIX

Tying top-down and bottom-up object and memory page lookups with the actual x86 page translation and segmentation