Answer includes concept of encapsulation in C# oops with various C# encapsulation examples with programs.
Answer:Encapsulation in C# is one of the oops principles that is used for hiding complexities in programs.
NOTE: Many candidates answer to this interview question “What is encapsulation in C#” like wrapping the class member fields into a method as a single unit”. This answer is partially correct and is not a good acceptable answer. In fact, the encapsulation definition should be just hiding the complexities in the program.
What does encapsulation mean? Simple definition of encapsulation is the process of hiding complexities in programs. So, whatever the ways we find to hide complexities or say information’s in C# object oriented programming, that is known as encapsulation process.
Here are some of the ways we hide information’s. (Program examples after points)
- Wrap class fields (data/variables) with public methods. – Using Getter and Setter
- Wrap class fields (data/variables) with get and set Properties
- Hide internal methods of class using private access specifiers etc.
1) Wrapping class fields with public method:
In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.
In below program, we have make the variable int a private, so, it cannot be accessible from outside of the class and have provided a public getter and setter methods or properties to access the variable int a. So, class field int a is hidden from outside world.
Example program with public getter and setter methods
class A {
private int a;
//Getter method
public int getA() {
return a;
}
//setter method
public void setA(int a) {
this.a = a;
}
}
Example program with Public get and set Properties
class A {
private int a;
public int A
{
get
{
return a;
}
set
{
this.a = A;
}
}
}
2)Hide internal methods of a class – by making them private
In below class m1() method is an internal method that is used by the class itself only and cannot be accessible outside of the class
class A {
// Hide internal method using private access specifier
// so it cannot be accessible from outside of the class
private void m1() {
}
// public method accessible outside of the class
public void m2() {
// Call internal method
m1();
}
}