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..
Note:
An encapsulated object is called as abstract data type.
Description
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.
Note
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.
More Info
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.
3.Interface
Example
[csharp]
public class StudentDetails
{
private string name;
public string GetName() //get method
{
return name;
}
public void SetName(string stuname) //set method
{
name=stuname
}
}
[/csharp]
In the below example you can see the basic example.
[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SPLessons
{
public class Company
{
private string company = "Govt";
// property which has get and set
public string CompanyName
{
get
{
return company; //get property
}
set
{
company = value; //set property
}
}
private string address = "India";
// readonly property
public string Address
{
get
{
return address; //return the value in address object
}
}
}
class Program
{
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("Company Details"+name);
Console.WriteLine("Address:" + address);
}
}
}
[/csharp]
Output: