Encapsulation in C#: Explained with Examples
Introduction
Encapsulation is one of the fundamental principles of Object-Oriented Programming (OOP) in C#. It helps in protecting the internal state of an object and ensures that data is accessed and modified safely. By encapsulating data, developers can control how their classes expose and manipulate information, leading to more secure, maintainable, and flexible applications.
What is Encapsulation in C#?
Encapsulation in C# refers to the practice of bundling data (fields) and methods (functions) that operate on that data into a single unit — a class. It also involves restricting direct access to some of an object’s components, which is typically done using access modifiers and properties.
In simple terms, encapsulation means "hiding the internal details" and only exposing what’s necessary. This concept is also known as data hiding.
Benefits of Encapsulation
- Data Protection: Prevents unauthorized access and modification of data.
- Improved Maintainability: Easier to modify code without breaking other parts of the program.
- Code Reusability: Well-encapsulated classes are more modular and reusable.
- Better Control: Allows developers to control how data is accessed and modified.
Understanding Access Modifiers in C#
Access modifiers define the visibility and accessibility of classes and class members. In C#, we commonly use:
public– Accessible from anywhere.private– Accessible only within the same class.protected– Accessible within the class and derived classes.internal– Accessible within the same assembly.protected internal– Accessible within the same assembly or derived classes.
private and expose them through public properties to maintain control over data access.
Example 1: Basic Encapsulation in C#
Let’s see a simple example that demonstrates how encapsulation works using private fields and public properties.
using System;
class Employee
{
// Private fields - data hiding
private string name;
private double salary;
// Public properties - controlled access
public string Name
{
get { return name; }
set { name = value; }
}
public double Salary
{
get { return salary; }
set
{
if (value > 0)
salary = value;
else
Console.WriteLine("Invalid salary amount!");
}
}
public void DisplayInfo()
{
Console.WriteLine($"Employee Name: {Name}");
Console.WriteLine($"Employee Salary: {Salary}");
}
}
class Program
{
static void Main()
{
Employee emp = new Employee();
// Using properties to set data
emp.Name = "John Doe";
emp.Salary = 50000;
emp.DisplayInfo();
// Attempting invalid data
emp.Salary = -1000;
}
}
In this example, the fields name and salary are private, so they cannot be accessed directly from outside the class. Instead, they are accessed through public properties that enforce validation rules.
Example 2: Auto-Implemented Properties for Simplicity
If you don’t need validation logic, you can simplify the class using auto-implemented properties.
class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
Student s1 = new Student { Name = "Alice", Age = 21 };
Console.WriteLine($"Name: {s1.Name}, Age: {s1.Age}");
}
}
This approach is concise and useful when encapsulation rules are minimal, though adding logic later is always possible by converting to a full property definition.
Example 3: Real-World Example – Bank Account Class
Here’s a more practical use case showing how encapsulation helps maintain data integrity in a banking application.
class BankAccount
{
private double balance;
public double Balance
{
get { return balance; }
private set { balance = value; }
}
public void Deposit(double amount)
{
if (amount > 0)
Balance += amount;
else
Console.WriteLine("Deposit amount must be positive.");
}
public void Withdraw(double amount)
{
if (amount > 0 && amount <= Balance)
Balance -= amount;
else
Console.WriteLine("Invalid withdrawal amount or insufficient balance.");
}
}
class Program
{
static void Main()
{
BankAccount account = new BankAccount();
account.Deposit(1000);
account.Withdraw(300);
Console.WriteLine($"Current Balance: {account.Balance}");
}
}
Here, the Balance property is read-only outside the class because of the private set. This ensures the balance can only be modified through the Deposit and Withdraw methods, enforcing business logic safely.
Best Practices for Using Encapsulation in C#
- Keep fields
privateand expose them throughpublicproperties. - Use access modifiers appropriately to control visibility.
- Implement validation logic in property setters.
- Use
readonlyorprivate setto make properties immutable when needed. - Group related data and methods into cohesive classes.
Conclusion
Encapsulation in C# is an essential concept in object-oriented programming that helps safeguard data, maintain clean architecture, and promote reusability. By using access modifiers, properties, and validation logic wisely, developers can create more robust and reliable applications.
What’s Next?
Now that you understand encapsulation, explore related OOP principles such as Inheritance and Polymorphism in C#. These concepts work together to help you write scalable and maintainable code.
If you found this guide helpful, consider sharing it with your developer community or bookmarking it for quick reference!
This Content Sponsored by SBO Digital Marketing. Mobile-Based Part-Time Job Opportunity by SBO! Earn money online by doing simple content publishing and sharing tasks. Here's how: Job Type: Mobile-based part-time work Work Involves: Content publishing Content sharing on social media Time Required: As little as 1 hour a day Earnings: ₹300 or more daily Requirements: Active Facebook and Instagram account Basic knowledge of using mobile and social media For more details: WhatsApp your Name and Qualification to 9025032394 a.Online Part Time Jobs from Home b.Work from Home Jobs Without Investment c.Freelance Jobs Online for Students d.Mobile Based Online Jobs e.Daily Payment Online Jobs Keyword & Tag: #OnlinePartTimeJob #WorkFromHome #EarnMoneyOnline #PartTimeJob #jobs #jobalerts #withoutinvestmentjob


0 Comments