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

王林
Release: 2023-08-24 22:13:03
forward
1252 people have browsed it

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

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

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!

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