Home  >  Article  >  Backend Development  >  How is encapsulation implemented in C#?

How is encapsulation implemented in C#?

WBOY
WBOYforward
2023-09-04 23:17:021296browse

How is encapsulation implemented in C#?

Encapsulation is achieved through the use of access specifiers. Access specifiers define the scope and visibility of class members. C# supports the following access specifiers: Public, Private, Protected, Internal, Protected Internal, etc.

Encapsulation can be understood through the private access specifier, which allows a class to hide its member variables and functions from other functions and objects.

In the following example, we have length and width as variables assigned private access specifiers -

Example

using System;

namespace RectangleApplication {
   class Rectangle {
      private double length;
      private double width;

      public void Acceptdetails() {
         length = 20;
         width = 30;
      }

      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();
         r.Acceptdetails();
         r.Display();
         Console.ReadLine();
      }
   }
}

The above is the detailed content of How is encapsulation implemented in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete