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
- Class class1
- {
- Public int x;
- Public int y;
- }
- Class class2
- {
- Public static void Main()
- {
- class1 c1 = new class1();
- C1.x = 3;
- C1.y = 5;
- Console.writeline(“x = {
- 0
- }, y = {
- 0
- }”, c1.x, c1.y);
- }
- }
Private - Access is limited to within the class definition.
- Private members are unable to use outside the class.
- Private is the default access modifier.
- Class emp
- {
- privateint salary = 10000;
- Public getsalary()
- {
- Return salary;
- }
- }
- Class Mainclass
- {
- Public static void main()
- {
- Emp e = new emp();
- Int s = e.getsalary();
- Console.writeline(“emp salary: ” + s);
- }
- }
Protected - Limited access within the class definition.
- We can access protected members using inheritance.
- Class class1
- {
- Protected int x = 10;
- }
- Class class2: class1
- {
- Public static void Main()
- {
- Class2 c2 = new class2();
- C2.x = 7;
- Console.writeline(“int value = ”, +c2.x);
- }
- }
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).
- Class access
- {
- internal string name;
- public void print()
- {
- Console.WriteLine("My name is " + name);
- }
- }
- }
- class Program
- {
- static void Main()
- {
- access ac = new access();
- Console.Write("Enter your name");
- variable ac.name = Console.ReadLine();
- ac.print();
- Console.ReadLine();
- }
- }