How is encapsulation implemented in C#?

WBOY
Release: 2023-09-04 23:17:02
forward
1328 people have browsed it

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();
      }
   }
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template