Encapsulation is a methodology that combines data and methods within a unified entity. Its purpose is to organize data attributes and member functions within a class. This encapsulated class incorporates getter and setter methods for retrieving and updating data. It also enforces controlled access to data by utilizing access modifiers, thereby limiting direct data manipulation.
The given CSS code snippet defines a class called "placeholder-diagram" with specific styling properties. This class sets a background color gradient, border radius, padding, margin, and text alignment for elements using it. Additionally, it includes a nested class "placeholder-icon" that determines the font size and margin-bottom for the icon within the placeholder diagram, and a "placeholder-text" class that sets the color and font size for the text content.
In C# development, encapsulation facilitates information concealment, concealing the inner workings of a class while revealing crucial details via public methods. This technique aids in safeguarding data integrity and enhancing security, ultimately enhancing code comprehensibility and maintainability.
Syntax of Encapsulation:
It has the following syntax:
class Classname
{
private dataType field_name; // Private field
public dataType Property_name // Property (getter & setter)
{
get { return fieldName; }
set { fieldName = value; }
}
}
In this syntax,
- class Classname: It represents the name of the class.
- private datatype field_name: It represents the private field that contains the data type and the field name.
- public dataType Property_name: It represents the properties that are declared as public.
- get: It is used to read the value of the private field.
- set: It is used to assign and modify the value of a private field.
C# Encapsulation Example:
Let's consider an example to demonstrate encapsulation in C#.
Example
using System;
namespace AccessSpecifiers
{
class Employee
{
// Private fields (data hidden from outside)
private string id;
private string name;
private string email;
// Public properties (controlled access)
public string ID
{
get { return id; }
set { id = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Email
{
get { return email; }
set { email = value; }
}
}
class C# Tutorial
{
static void Main(string[] args)
{
Employee emp = new Employee();
// Set values using properties
emp.ID = "101";
emp.Name = "George";
emp.Email = "George@example.com";
// Get values using properties
Console.WriteLine("ID = " + emp.ID);
Console.WriteLine("Name = " + emp.Name);
Console.WriteLine("Email = " + emp.Email);
}
}
}
Output:
ID = 101
Name = George
Email = George@example.com
Explanation:
In this instance, we've illustrated a scenario where an Employee class conceals its internal variables (id, name, email) through the private declaration. Subsequently, we establish access to these attributes using public properties (ID, Name, Email) that serve as accessors and mutators. This approach guarantees regulated entry and safeguards the underlying information, all the while permitting secure read and write actions externally to the class.
Why We Need Encapsulation in C#
There are several case that shows the need for encapsulation in C#. Some of them are as follows:
- Encapsulation hides internal details and protects it against unauthorized access.
- It offers data control through validating in properties.
- It makes the code more maintainable because internal modifications do not impact external code.
- It enhances readability and maintains the program well-organized.
Access Modifiers in C# Encapsulation
In C# coding, access modifiers determine the accessibility of class members (such as fields, methods, and properties) within the class or from outside. These modifiers play a crucial role in encapsulation, a fundamental concept in Object-Oriented Programming (OOP). C# includes primarily five access modifier types:
The <style> element defines a CSS style for a placeholder diagram. This diagram has a background color created with a linear gradient, rounded corners with a border radius of 12 pixels, generous padding, and centered text. Additionally, it includes an icon with a size of 3 rem and a text with a font size of 1 rem, both styled in a specific color.
Here, we will explore each of these access modifiers individually.
1) Public Access Modifier
The public access modifier is the most commonly used specifier for accessibility in C#. It is accessible from both within and outside the class, allowing any code to reach the type or member within the current assembly or from another assembly that has a reference to it.
C# Public Access Modifier Example
Let's consider a scenario to demonstrate the public access specifier within C# encapsulation.
Example
using System;
namespace CarExample
{
class Car
{
public string Model;
public void ShowModel()
{
Console.WriteLine("Car Model: " + Model);
}
}
class C# Tutorial
{
static void Main()
{
Car car = new Car();
car.Model = "Porsche";
car.ShowModel();
}
}
}
Output:
Car Model: Porsche
Explanation:
In this instance, we are examining the class Car. Subsequently, we define a public field named Model, enabling direct access and modification from external sources to the Car class. Ultimately, we employ the DisplayModel function to exhibit the specific car model specified within the primary function.
2) Private Access Modifier
The private access specifier limits its access exclusively to the classes or structs in which it is defined. It is inaccessible outside the class, representing the strictest level of access control.
Private Access Modifier Example in C#
Let's consider an example to demonstrate the private access modifier in C#.
Example
using System;
class BankAccount
{
private double balance;
public void Deposit(double amount)
{
if (amount > 0)
{
balance += amount;
}
}
public void Withdraw(double amount)
{
if (amount > 0 && amount <= balance)
{
balance -= amount;
}
else
{
Console.WriteLine("Invalid withdraw amount!");
}
}
public double GetBalance()
{
return balance;
}
}
class Program
{
static void Main()
{
BankAccount account = new BankAccount();
account.Deposit(5000);
Console.WriteLine("Balance: " + account.GetBalance());
account.Withdraw(1000);
Console.WriteLine("Balance after withdrawal: " + account.GetBalance());
}
}
Output:
Balance: 5000
Balance after withdrawal: 4000
Explanation:
In this instance, we employ a BankAccount class featuring a concealed balance field to restrict direct access. Accessible methods facilitate adding funds, subtracting funds, and fetching the current balance. Within the Main method, a new account object is instantiated, money is deposited and withdrawn, and the balance is exhibited.
3) Protected Access Modifier
Protected access control allows access to class members within the same class and by any derived classes. This feature grants child classes the ability to interact with member variables and member functions from their parent class. Its primary purpose is to facilitate inheritance with restricted access.
Protected Access Modifier Example in C#
Let's consider a scenario to demonstrate the protected access modifier in C#.
Example
using System;
namespace ProtectedExample
{
class Person
{
protected string name;
public void SetName(string n)
{
name = n;
}
}
class Student : Person
{
public void ShowName()
{
Console.WriteLine("Student Name: " + name);
}
}
class Program
{
static void Main()
{
Student s = new Student();
s.SetName("Michael");
s.ShowName();
}
}
}
Output:
Student Name: Michael
Explanation:
In this instance, we showcase the concepts of inheritance and encapsulation. We showcase a Person class with a protected name field, ensuring it cannot be accessed directly but is accessible within the derived Student class. The SetName method is responsible for assigning a value to the name field, while ShowName is used to display it. Within the Main method, an instance of Student is created to set and showcase the name.
5) Internal Access Modifier
The internal access modifiers grant access within the program at the same assembly level where they are declared, but restrict access from another assembly.
Internal Access Modifier Example in C#
Let's consider a scenario to demonstrate the internal access modifier in C#.
Example
using System;
namespace Internal
{
internal class Calculator
{
internal int Add(int a, int b)
{
return a + b;
}
internal int Multiply(int a, int b)
{
return a * b;
}
}
class Program
{
static void Main()
{
Calculator calc = new Calculator();
Console.WriteLine("Sum: " + calc.Add(6, 27));
Console.WriteLine("Product: " + calc.Multiply(4, 17));
}
}
}
Output:
Sum: 33
Product: 68
Explanation:
In this instance, we define an internal class named Calculator containing methods for addition and multiplication. Since the class is internal, its visibility is restricted to the same assembly. Within the Main method, an instance of the Calculator class is created and employed to display the results of addition and multiplication operations.
5) Protected Internal Access Modifier
In C# development, the protected internal access modifier is a blend of the protected and internal access modifiers. Members with the protected internal access modifier are accessible within the identical assembly and in subclasses, regardless of whether those subclasses exist in another assembly.
Protected Internal Access Modifier Example in C#
Let's consider a scenario to demonstrate the protected internal access modifier in C#.
Example
using System;
namespace ProtectedInternal
{
class Employee
{
protected internal string Name;
protected internal int Salary;
public void SetDetails(string name, int salary)
{
Name = name;
Salary = salary;
}
}
class Manager : Employee
{
public void ShowDetails()
{
Console.WriteLine("Manager Name: " + Name);
Console.WriteLine("Manager Salary: " + Salary);
}
}
class Program
{
static void Main()
{
Manager mgr = new Manager();
mgr.Name = "Jhonson";
mgr.Salary = 80000;
mgr.ShowDetails();
Employee emp = new Employee();
emp.SetDetails("David", 50000);
Console.WriteLine("Employee Name: " + emp.Name);
Console.WriteLine("Employee Salary: " + emp.Salary);
}
}
}
Output:
Manager Name: Jhonson
Manager Salary: 80000
Employee Name: David
Employee Salary: 50000
Explanation:
In this instance, we are considering a class Employee where two attributes have been defined. Subsequently, the attributes Name and Salary can be accessed within the subclass (Manager) and also directly from the Program class since they belong to the identical assembly.
Comparison Table of Access Specifiers
The subsequent table illustrates the contrast among these specifiers in C#.
| Specifier | Same Class | Derived Class (Same Assembly) | Other Classes (Same Assembly) | Other Assembly |
|---|---|---|---|---|
| Public | Yes | Yes | Yes | Yes |
| Private | Yes | No | No | No |
| Protected | Yes | Yes | No | No |
| Internal | Yes | Yes | Yes | No |
| Protected Internal | Yes | Yes | Yes | Yes (Derived only) |
| Private Protected | Yes | Yes (Same Assembly only) | No | No |
C# Encapsulation through Properties
In C#, utilizing properties is the recommended approach for implementing encapsulation. Instead of directly revealing fields, we can declare them as private and manage access through getter and setter properties.
C# Encapsulation Example Using Properties
Let's consider an example to demonstrate encapsulation through properties in C#.
Example
using System;
class Employee
{
private string name;
private int age;
public string Name
{
get { return name; }
set
{
if (!string.IsNullOrEmpty(value))
name = value;
else
Console.WriteLine("Invalid Name!");
}
}
public int Age
{
get { return age; }
set
{
if (value > 0 && value <= 60)
age = value;
else
Console.WriteLine("Invalid Age! Must be between 1 and 60.");
}
}
}
class C# Tutorial
{
static void Main()
{
Employee emp = new Employee();
emp.Name = "Jackson";
emp.Age = 42;
Console.WriteLine("Name of the Employee : " + emp.Name);
Console.WriteLine("Age of the Employee : " + emp.Age);
emp.Name = "";
emp.Age = 87;
}
}
Output:
Name of the Employee : Jackson
Age of the Employee : 42
Invalid Name!
Invalid Age! Must be between 1 and 60.
Explanation:
In this instance, we showcase encapsulation by using private fields for name and age, and exposing them through public properties Name and Age. These properties employ getters to retrieve values and setters to validate input before assigning. Within the Main method, values are passed using properties, where valid inputs are acknowledged and displayed, while invalid inputs trigger error messages.
Advantages of Encapsulation in C#
Several advantages of encapsulation in C# are as follows:
- It stores internal object information securely by restricting direct manipulation and exposing only necessary data through properties or methods.
- It prevents unauthorized use and maintains internal data in a secure manner.
- We can change the internal structure of a class without affecting other sections of the program.
- It is easy to make and change code because internal changes don't interfere with external code that uses the class.
- Encapsulated classes are sealed; therefore, they can be used on different projects.
Disadvantages of Encapsulation in C#
Several disadvantages of encapsulation in C# are as follows:
- If we add getters and setters for every field, it can lengthen the code and make it complex to read.
- Method/property data access may be slightly less efficient than direct field access.
- Poorly designed encapsulation can reduce its benefits.
C# Encapsulation FAQs
1) What is encapsulation in C#?
In C# coding, encapsulation refers to the act of bundling together data (fields) and functionalities (methods) within a unified entity (class). It includes restricting direct entry to class elements to uphold data consistency.
2) Why is Encapsulation important in C#?
It safeguards the integrity of objects by concealing internal state and enforcing interaction through the object's methods. This prevents unauthorized usage and misuse, ensuring controlled access and modification.
3) Can we encapsulate without properties in C#?
Yes, employing private fields along with getter and setter methods is one approach. However, properties (get and set) are currently the preferred method.
4) What sets encapsulation apart from abstraction?
Encapsulation involves concealing the inner workings of data storage and manipulation to prioritize data security.
Abstraction: It conceals the intricate details of method implementation while revealing essential functionality.
5) What is the most commonly used access modifier for implementing encapsulation?
In C# development, the private access modifier is frequently employed for encapsulation to guarantee data concealment through limiting direct entry to fields. Different access modifiers may be chosen based on the desired extent of visibility.