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

CsharpProgrammingServer Side Programming

Public access specifier 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 below example the variables length and width have been declared public. Now you can even access them outside the Main() method.

The variables are accessed using the instance of the class.

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

Let us see 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();
      }
   }
}
raja
Published on 17-Sep-2018 08:59:22
Advertisements