Encapsulation in C#

CsharpProgrammingServer Side Programming

Encapsulation in C# prevents access to implementation details. Implement Encapsulation in C# using access specifiers.

The following are the access specifiers supported by C#.

  • Public
  • Private
  • Protected
  • Internal
  • Protected internal

Encapsulation can be understood by taking an example of private access specifier that allows a class to hide its member variables and member functions from other functions and objects.

In the following example we have length and width as variables assigned private access specifier.


 Live Demo

using System;
namespace RectangleApplication {
   class Rectangle {
      private double length;
      private double width;
      public void Acceptdetails() {
         length = 10;
         width = 15;
      public double GetArea() {
         return length * width;
      public void Display() {
         Console.WriteLine("Length: {0}", length);
         Console.WriteLine("Width: {0}", width);
         Console.WriteLine("Area: {0}", GetArea());
   class ExecuteRectangle {
      static void Main(string[] args) {
         Rectangle r = new Rectangle();


Length: 10
Width: 15
Area: 150
Published on 17-Sep-2018 08:46:27