Encapsulation Example in C# - Biz Tech

Encapsulation Example in C#

Listen
using System;

class Program
{
    static void Main(string[] args)
    {
        BankAccount account = new BankAccount("John Smith", 1000);

        Console.WriteLine(account.Balance);

        account.Deposit(500);

        Console.WriteLine(account.Balance);

        account.Withdraw(200);

        Console.WriteLine(account.Balance);
    }
}

class BankAccount
{
    private string owner;
    private double balance;

    public BankAccount(string owner, double balance)
    {
        this.owner = owner;
        this.balance = balance;
    }

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

    public void Deposit(double amount)
    {
        Balance += amount;
    }

    public void Withdraw(double amount)
    {
        if (amount > Balance)
        {
            throw new ArgumentException("Insufficient balance.");
        }

        Balance -= amount;
    }
}
 

In this example, we have a BankAccount class that represents a simple bank account. The class has private fields owner and balance, which are encapsulated and can only be accessed through public methods. The Balance property has a private setter, which ensures that the balance can only be set internally within the class, and not from outside.

The BankAccount class also has methods for depositing and withdrawing money, which update the balance and enforce business rules. For example, the Withdraw() method checks whether the requested withdrawal amount is greater than the account balance, and throws an exception if it is.

In the Main() method, we create a BankAccount object and perform some operations on it, such as depositing and withdrawing money. We can access the account’s balance through the Balance property, but we cannot modify it directly because it is encapsulated.

This example demonstrates encapsulation, where the internal workings of a class are hidden from the outside world and can only be accessed through well-defined public methods and properties. This improves the safety and maintainability of the code by reducing the risk of unintended modification or misuse.