Computer >> Computer tutorials >  >> Programming >> C#

What are the differences between public, protected and private access specifiers in C#?


Public Access Specifier

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.

Example

using System;
namespace Demo {
   class Rectangle {
      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 = 7;
         r.width = 10;
         r.Display();
         Console.ReadLine();
      }
   }
}

Output

Length: 7
Width: 10
Area: 70

Protected Access Specifier

Protected access specifier allows a child class to access the member variables and member functions of its base class.

Let us see an example of protected access modifier, accessing the protected members.

Example

using System;
namespace MySpecifiers {
   class Demo {
      protected string name = "Website";
      protected void Display(string str) {
         Console.WriteLine("Tabs: " + str);
      }
   }
   class Test : Demo {
      static void Main(string[] args) {
         Test t = new Test();
         Console.WriteLine("Details: " + t.name);
         t.Display("Product");
         t.Display("Services");
         t.Display("Tools");
         t.Display("Plugins");
      }
   }
}

Output

Details: Website
Tabs: Product
Tabs: Services
Tabs: Tools
Tabs: Plugins

Private Access Specifier

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

Example

using System;
namespace Demo {
   class Rectangle {
      //member variables
      private double length;
      private double width;
      public void Acceptdetails() {
         length = 10;
         width = 15;
      }
      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: 15
Area: 150