Encapsulation refers to the concept of combining data (variables) and the methods (functions) that manipulate this data into a unified entity or class. This principle also involves limiting access to certain elements by designating them as private or protected. By concealing the internal workings, encapsulation ensures that only essential information is made available, thereby enhancing the management of data access and modification.
Example
using System;
namespace EncapsulationExample
{
public class UserBankAccountDetails
{
// Encapsulated private fields
private string accountNumber;
private decimal initialBalance;
// Constructor to initialize account details
public UserBankAccountDetails(string accountNumber, decimal initialBalance)
{
this.accountNumber = accountNumber;
this.initialBalance = initialBalance;
}
// Public method to get the account balance
public decimal GetUserBalance()
{
return initialBalance;
}
// Public method to deposit money
public void AmountDepositedByUser(decimal amount)
{
if (amount > 0)
initialBalance += amount;
else
throw new ArgumentException("Deposit amount must be positive.");
}
// Public method to withdraw money
public void GetAmountWithdrawnByUser(decimal amount)
{
if (amount > 0 && amount <= initialBalance)
initialBalance -= amount;
else
throw new ArgumentException("Invalid withdraw amount.");
}
}
class Program
{
static void Main()
{
UserBankAccountDetails useraccount = new UserBankAccountDetails("01245431", 2000);
// Accessing the balance via controlled methods (Encapsulation)
useraccount.AmountDepositedByUser(500); // Deposit $500
useraccount.GetAmountWithdrawnByUser(200); // Withdraw $200
// Attempt to withdraw more than balance (Controlled validation)
// useraccount.GetAmountWithdrawnByUser(400); // Invalid withdrawal
// Checking balance using a controlled method
Console.WriteLine($"Final Balance: {useraccount.GetUserBalance():C}");
}
}
}
Explanation of the above-encapsulated class
- Private Field: The balance field is private, meaning it cannot be accessed directly from outside the UserBankAccountDetails.cs class. This hides the internal state from the outside world.
- Public Methods: AmountDepositedByUser, GetAmountWithdrawnByUser, and GetUserBalance methods provide controlled access to the private initialBalance field. They ensure that the balance is only modified in a valid way.
- The AmountDepositedByUser method checks that the deposit amount is positive.
- The GetAmountWithdrawnByUser method ensures that withdrawals are valid (not greater than the current balance).
- These methods ensure that the balance can only be changed through safe and meaningful operations, preventing invalid operations from being performed.
- Data Integrity: The logic inside Deposit and GetAmountWithdrawnByUser maintains data integrity by preventing invalid data (e.g., negative deposits or withdrawals exceeding the balance).
Advantages of Encapsulation
- Enhanced Security: Sensitive information can be concealed from external access, allowing it to be revealed only in a regulated manner. This prevents unauthorized code from altering the internal state.
- Easier Maintenance: Modifications to the internal workings of a class (such as how the balance is calculated or stored) can be executed without impacting external code. Provided that the interface (public methods) remains unchanged, other components of the application will not require adjustments.
- Regulated Data Modification: By managing how data is accessed and altered, it is possible to impose rules (for instance, disallowing invalid values) and guarantee that the object consistently maintains a valid state.
- Adaptability and Extensibility: Encapsulation enables changes to internal implementations or logic without necessitating alterations to the external contract. This characteristic enhances the flexibility of the code and facilitates easier future extensions.
Encapsulation focuses on safeguarding the internal state of an object by concealing its data and offering a regulated method for accessing and altering that data. This approach guarantees that the object retains a valid state, facilitates maintenance, enhances security, and contributes to a more resilient and manageable system.
Abstraction emphasizes concealing the implementation specifics of a system while presenting only the essential functionalities. In C#, abstraction is realized through the use of abstract classes or interfaces, allowing the user to be aware of the methods or properties without being exposed to the underlying code that facilitates their operation.
Example of Abstraction in C# using Interface
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractionExample
{
public interface IVehicleDetails
{
void StartVehicle();
void StopVehicle();
void DriveVehicle();
}
public class CarMechanism : IVehicleDetails
{
public void StartVehicle()
{
Console.WriteLine("Car engine started.");
}
public void StopVehicle()
{
Console.WriteLine("Car has stopped.");
}
public void DriveVehicle()
{
Console.WriteLine("Car is driving.");
}
}
public class BikeMechanism : IVehicleDetails
{
public void StartVehicle()
{
Console.WriteLine("Bike engine started.");
}
public void StopVehicle()
{
Console.WriteLine("Bike has stopped.");
}
public void DriveVehicle()
{
Console.WriteLine("Bike is driving.");
}
}
}
public class Program
{
static void Main(string[] args)
{
IVehicleDetails myVehicle = new CarMechanism();
myVehicle.StartVehicle(); // Outputs: Car engine started.
myVehicle.DriveVehicle(); // Outputs: Car is driving.
myVehicle.StopVehicle(); // Outputs: Car has stopped.
myVehicle = new BikeMechanism();
myVehicle.StartVehicle(); // Outputs: Bike engine started.
myVehicle.DriveVehicle(); // Outputs: Bike is driving.
myVehicle.StopVehicle(); // Outputs: Bike has stopped.
}
}

Join the conversation! Your thoughts help the community grow.