Encapsulation in C# – Private & Public

Encapsulation in C#


Encapsulation is a methodology in C# Programming language.  In terms of dictionary explanation, Encapsulation is the action of enclosing something in or as if a capsule. 

Encapsulation in C# Practice & Benefits

In C# (or other Object-Oriented Programming), Encapsulation wraps up of data under a single unit (class); and the data wrapped up can be variables or methods.  

Encapsulation prevents unnecessary access to implementation details.  It establishes a protective shield that prevents the data from being accessed by code outside the shield.  


Encapsulation is practised by using access specifiers.  C# Support five access specifiers:

  • Public
  • Private
  • Protected
  • Internal
  • Protected internal

In this post, we mainly focus on Private & Public.

  • Private, enable a class to hide its variables or method from other class or class instance(object).  Inside the class, variables or methods can only be accessed by function within the class.  Other instances cannot access them, even though the instance of the class.
  • Public, compared with Private, Public is relatively simple.  Public allows any functions or objects to access its variables or methods.

Talk Is Cheap, Show Me The Code

As you can see, we make a calculator which performs a plus function.  This console program output a sum result of variable a and b.  In the Calculator class, we declare both a and b are private.  The approach of assigning values to these two variables is by calling the Calculator’s internal function Acceptdetails() and Acceptdetails() function is declared as public.

Otherwise, compilers will issue an error.


Private and Public access specifiers are useful in C# development. As our project become complex, we need to protect class integrity. Otherwise, it may trigger an accident corruption.

Email Subscription

Leave a Reply

Your email address will not be published. Required fields are marked *