Encapsulation in Object Oriented Programming C#

  • A software development technique in which each module’s interfaces reveal as little as possible about the module’s inner working and other modules are prevented from using information about the module that is not in the module’s interface specification.

What is Encapsulation ? 

  1. Encapsulation is a process of hiding the members from outside of class and implemented using access specifiers
  2. Encapsulation is also called as information hiding.
  3. Encapsulation provides a way to preserve the integrity of state data. Rather than defining public fields, private data fields should be defined.
  4. Well-encapsulated class should hide its data and the details of how it operates on data from the outside world. This is termed black box programming.
  5. Using this,implementation of the method can be changed by the class author without breaking any existing code making use of it.
An access specifier defines the scope and visibility of a class member. C# supports the following access specifiers:
  • Public
  • Private
  • Protected
  • Internal
  • Protected internal

Public Access Specifier:  

Public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be accessed from outside the class.


Private Access Specifier: 

Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members.

Protected Access Specifier:

Protected access specifier allows a child class to access the member variables and member functions of its base class. This way it helps in implementing inheritance

Internal Access Specifier:

Internal access specifier allows a class to expose its member variables and member functions to other functions and objects in the current assembly. In other words, any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined.