C# Encapsulation is a process of binding data members and member functions into a single component.
Encapsulation means protecting important data inside the class to not expose the data outside of the class.
The best example where encapsulation can be seen is in a car, class..
An encapsulated object is called as abstract data type.
Encapsulation is implemented by using access specifiers. An access specifier defines the scope and visibility of a class member. Below are access specifiers supported by C#.
Public: The type or member can be accessed by any other code in the same assembly or another assembly that references it.
Private: The type or member can only be accessed by code in the same class or struct.
Protected: The type or member can only be accessed by code in the same class or struct or in a derived class.
Internal: The type or member can be accessed by any code in the same assembly, but not from another assembly.
Protected Internal: The type or member can be accessed by any code in the same assembly or by any derived class in another assembly.
When no access modifier is set, a default access modifier is used. So there is always some form of access modifier even if it's not set.
Encapsulation is possible with accessor mutator(get or set method), properties and Interface
1.Accessor-mutator(get and set)
2.Properties: Read only and write only property.
public class StudentDetails
private string name;
public string GetName() //get method
public void SetName(string stuname) //set method
In the below example you can see the basic example.
public class Company
private string company = "Govt";
// property which has get and set
public string CompanyName
return company; //get property
company = value; //set property
private string address = "India";
// readonly property
public string Address
return address; //return the value in address object
static void Main()
// Encapsulation using properties
string name = string.Empty;
Company obj = new Company();
// call get part
name = obj.CompanyName;
// change the value
name = "Company Details!";
// call set part
obj.CompanyName = name;
string address = string.Empty;
// call readonly property
address = obj.Address;
// now address has value “India”
Console.WriteLine("Address:" + address);