Home >Backend Development >C#.Net Tutorial >What is the scope of public member variables of a class in C#?

What is the scope of public member variables of a class in C#?

王林
王林forward
2023-08-24 22:13:031271browse

What is the scope of public member variables of a class in C#?

Public access modifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be accessed from outside the class.

In the following example, the variables length and width have been declared public. Now you can access them even outside the Main() method.

These variables are accessed using instances of the class.

Rectangle r = new Rectangle();
r.length = 4.5;
r.width = 3.5;

Let’s look at the complete code.

Example

Using System;
namespace RectangleApplication {
   class Rectangle {
      // member variables
      public double length;
      public double width;
      public double GetArea() {
         return length * width;
      }
      public void Display() {
         Console.WriteLine("Length: {0}", length);
         Console.WriteLine("Width: {0}", width);
         Console.WriteLine("Area: {0}", GetArea());
      }
   } // end class Rectangle
   class ExecuteRectangle {
      static void Main(string[] args) {
         Rectangle r = new Rectangle();
         r.length = 4.5;
         r.width = 3.5;
         r.Display();
         Console.ReadLine();
      }
   }
}

The above is the detailed content of What is the scope of public member variables of a class 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