When you have such type of data in which you need the grouping of related operation into single unit, You can use encapsulation. Access modifier (such as Private, Public, Protected, Interval etc.) can be used for achieving the encapsulation. The encapsulation is used most commonly for data hiding.
Real-World Example of Encapsulation:
1. Capsule is one of the real-world examples of encapsulation, as the capsule binds all its medicinal materials within it. In the same way, C# Encapsulation, i.e., units (class, interface, enums, structs, etc) encloses all its data member and member functions within it.
2. Another real-world example of encapsulation can be your fruit backet. The backet contains different fruits like a Mango, Oranges, Apple, etc it. To get any fruit, you need to open that backet. Similarly, in C#, an encapsulation unit contains its data and behavior within it, and in order to access them, you need an object of that unit.
3. Another real-world example of encapsulation can be your sweet backet. The backet contains different sweets like a Rasgulla, Apple cake, Red velvet, etc it. To get any sweet, you need to open that backet. Similarly, in C#, an encapsulation unit contains its data and behavior within it, and in order to access them, you need an object of that unit.
In below example, We have Fruit class which have FruitName, FruitPrice properties and these properties will use here for hiding data. We have encapsulated name and price fields in FruitName, FruitPrice properties.
using System;
classCSharpTutorial
{
staticvoid Main(string[] arge)
{
Fruit fruit = new Fruit();
fruit.FruitName = "Mango";
fruit.FruitPrice = 100;
Console.WriteLine("Fruit Name is = {0}", fruit.FruitName);
Console.WriteLine("Fruit Price is = {0}", fruit.FruitPrice);
}
}
// parent class
publicclassFruit
{
privatestring? fruitName;
privateint fruitPrice;
//FruitName and FruitPrice Properties
publicstring FruitName
{
get { return name; }
set { name = value; }
}
publicint FruitPrice
{
get { return price; }
set { price = value; }
}
}
using System;
classCSharpTutorial
{
staticvoid Main(string[] arge)
{
Fruit fruit = new Fruit();
fruit.FruitName = "Mango";
fruit.FruitPrice = 100;
Console.WriteLine("Fruit Name is = {0}", fruit.FruitName);
Console.WriteLine("Fruit Price is = {0}", fruit.FruitPrice);
}
}
// parent class
publicclassFruit
{
privatestring? fruitName;
privateint fruitPrice;
//FruitName and FruitPrice Properties
publicstring FruitName
{
get { return name; }
set { name = value; }
}
publicint FruitPrice
{
get { return price; }
set { price = value; }
}
}
Output
Fruit Name is = Mango
Fruit Price is = 100
Summary
The encapsulation is used for promoting the modularity, maintainability, and security in your code.