Overview On Access Modifiers

Access modifiers

Access modifiers are an integral part of object-oriented programming. These keywords are used to specify the declared accessibility of a member or a type.

We have 4 types of access modifiers

  • Public
  • Private
  • Protected
  • Internal

Public

  • There are no restrictions on accessing public members.
  • We can access public members anywhere in the code.

Example

  1. Class class1   
  2. {  
  3.     Public int x;  
  4.     Public int y;  
  5. }  
  6. Class class2   
  7. {  
  8.     Public static void Main()  
  9.     {  
  10.         class1 c1 = new class1();  
  11.         C1.x = 3;  
  12.         C1.y = 5;  
  13.         Console.writeline(“x = {  
  14.             0  
  15.         }, y = {  
  16.             0  
  17.         }”, c1.x, c1.y);  
  18.     }  
  19. }
Private
  • Access is limited to within the class definition.
  • Private members are unable to use outside the class.
  • Private is the default access modifier.
  1. Class emp  
  2. {  
  3.     privateint salary = 10000;  
  4.     Public getsalary()   
  5.     {  
  6.         Return salary;  
  7.     }  
  8. }  
  9. Class Mainclass   
  10. {  
  11.     Public static void main()  
  12.     {  
  13.         Emp e = new emp();  
  14.         Int s = e.getsalary();  
  15.         Console.writeline(“emp salary: ” + s);  
  16.     }  
Protected
  • Limited access within the class definition.
  • We can access protected members using inheritance.
  1. Class class1  
  2. {  
  3.     Protected int x = 10;  
  4. }  
  5. Class class2: class1   
  6. {  
  7.     Public static void Main()  
  8.     {  
  9.         Class2 c2 = new class2();  
  10.         C2.x = 7;  
  11.         Console.writeline(“int value = ”, +c2.x);  
  12.     }  
  13. }
Internal
  • We can declare a class as internal or its members as internal.
  • Internal members are accessible only within files in the same assembly (.dll).
  1. Class access  
  2. {  
  3.     internal string name;  
  4.     public void print()  
  5.     {  
  6.         Console.WriteLine("My name is " + name);  
  7.     }  
  8. }  
  9. }  
  10. class Program   
  11. {  
  12.     static void Main()   
  13.     {  
  14.         access ac = new access();  
  15.         Console.Write("Enter your name");  
  16.         variable ac.name = Console.ReadLine();  
  17.         ac.print();  
  18.         Console.ReadLine();  
  19.     }  
Ebook Download
View all
Learn
View all