0
0
C Sharp (C#)programming~5 mins

Why encapsulation matters in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Encapsulation helps keep data safe and hides details inside a class. It makes programs easier to understand and change.

When you want to protect important data from being changed directly.
When you want to hide complex details and show only simple actions.
When you want to control how data is accessed or updated.
When you want to make your code easier to fix or improve later.
When you want to keep parts of your program separate and organized.
Syntax
C Sharp (C#)
class ClassName
{
    private int data; // hidden data

    public int GetData()
    {
        return data;
    }

    public void SetData(int value)
    {
        if (value >= 0) // control access
            data = value;
    }
}

private means the data is hidden from outside the class.

Use public methods to safely get or set the data.

Examples
This example hides the balance and only allows adding money through Deposit.
C Sharp (C#)
class BankAccount
{
    private double balance;

    public double GetBalance()
    {
        return balance;
    }

    public void Deposit(double amount)
    {
        if (amount > 0)
            balance += amount;
    }
}
This uses a property to control access to the name, making sure it is not empty.
C Sharp (C#)
class Person
{
    private string name;

    public string Name
    {
        get { return name; }
        set { if (!string.IsNullOrEmpty(value)) name = value; }
    }
}
Sample Program

This program shows how encapsulation protects the speed value. It only allows valid speeds between 0 and 200.

C Sharp (C#)
using System;

class Car
{
    private int speed;

    public int Speed
    {
        get { return speed; }
        set
        {
            if (value >= 0 && value <= 200)
                speed = value;
        }
    }
}

class Program
{
    static void Main()
    {
        Car myCar = new Car();
        myCar.Speed = 150; // set speed safely
        Console.WriteLine($"Car speed is {myCar.Speed} km/h");

        myCar.Speed = -10; // invalid speed, ignored
        Console.WriteLine($"Car speed after invalid set: {myCar.Speed} km/h");
    }
}
OutputSuccess
Important Notes

Encapsulation helps avoid bugs by controlling how data changes.

It makes your code safer and easier to maintain.

Summary

Encapsulation hides data inside classes to protect it.

Use private fields and public methods or properties to control access.

This keeps your program organized and easier to fix or improve.