Abstraction and Encapsulation in C#

Sachin Hegadepatil
2 min readMar 11, 2020

--

Abstraction and encapsulation are similar features in object-oriented programming. Both have their own advantages at there level.

Abstraction

Abstraction is the process of hiding the style of work of an object and showing the useful information which is required to understand the object. Abstraction puts all variables and methods in a class that is necessary. It is an act of identifying the behavior of an object that should be possessed. It solves the problem at the design level.

Abstraction can be achieved by abstract classes in C# and it allows us to create abstract classes that are used to provide a partial implementation and implementation can be done when derived class inherit from it. Abstract class contains the abstract methods which are implemented in the derived classes.

There are some keys points about the abstract classes:-

  1. you cannot create the instance of an abstract class.
  2. you cannot declare the abstract method outside the abstract class.
  3. abstract classed cannot be sealed (when you make a sealed class then you cannot inherit it). but abstract class contains the sealed classes.
  4. A subclass of an abstract class only can be instantiated if it implements all of the abstract methods of its superclass.
  5. We cannot declare abstract methods as private.

Why we cannot instantiate the abstract class?

If the compiler allows us to create the object of abstract class then we can invoke the abstract methods using the object which cannot be executed by the CLR at runtime.

A basic example of how we use abstract classes and methods.

Encapsulation

Encapsulation enables the programmer to implement the desired level of abstraction. It is a process of hiding all internal details of the object from outside the world. We hide data making it private and expose a public property to access those data from outside the world.

Encapsulation protects data from unwanted access or altered. it is the mechanism where the abstraction is implemented. It solves the problem at the implementation level.

The encapsulated class won’t allow us to access the fields directly instead, we need to use the getter and setter to access functions to read and write data based on requirements.

A basic example to achieve encapsulation.

hope you understood the basics of these concepts.

--

--