In C# encapsulation is a process that combines data members and functions together into a single unit. In other words, 'putting data and functions together within a single class is called encapsulation.' Due to encapsulation, we cannot access the data directly and it can be accessed only through the functions of the class. This is the most important feature of OOPs (object-oriented programming). Due to encapsulation, the data remains safe and is not misused.
How do you achieve Encapsulation in a Class?
1. By making all data members private.
2. By creating public setter and getter functions for all data members.
Types of Encapsulation in C#
1. Member Variable Encapsulation – In this encapsulation, all the data members are declared as private.
2. Function encapsulation – In this, some member functions are made private. The constructor is kept public.
3. Class encapsulation – In this, all classes are kept private. This is mostly done during nested classes.
Advantage of Encapsulation
1. In C#, with the help of encapsulation, we can keep related data and functions together. Due to which our code remains clean and the code is easy to read.
2. Through Getter and Setter functions we can provide read-only or write-only access to our class members.
3. By this data hiding and data abstraction can be achieved.
Syntax
namespace namespace-name{
[access modifier] class class-name
{
// [access modifier] datatype variable-name
// [access modifier] datatype property-name{
Setter statement
Getter statement
}
// [access modifier] datatype function-name{
Function satement
}
}
}
Example
namespace ENC.Com{
public class EncapsulationDemo
{
private int Size;
public int RowSize{
set{
Size=value;
}
get{
return Size;
}
}
public int GetSize(){
return Size;
}
}
}
using System;
public class Circle
{
private const float PI=3.14159f;
private int Size;
public int Radius{
set{
Size=value;
}
get{
return Size;
}
}
public float GetArea
{
get{
return GetTotalSize();
}
}
private float GetTotalSize(){
return Size * Size * PI;
}
}
public class Program
{
public static void Main()
{
Circle circle=new Circle();
circle.Radius=5;
Console.WriteLine('Area : '+circle.GetArea);
}
}
Output
Area : 78.53975