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


Only functions of the same class can access its private members. Private access specifier allows a class to hide its member variables and member functions from other functions and objects.

Example

 Live Demo

using System;
namespace RectangleApplication {
   class Rectangle {
      //member variables
      private double length;
      private double width;
      public void Acceptdetails() {
         length = 10;
         width = 14;
      }
      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.Acceptdetails();
         r.Display();
         Console.ReadLine();
      }
   }
}

Output

Length: 10
Width: 14
Area: 140

Above, the variable length and width are declared private; therefore the methods of the same class can access it.

Updated on: 23-Jun-2020

279 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements