Access Specifiers (Access Modifiers) are keywords in Object Oriented Programming, that specify accessibility of Types and Types Members.
Remember the following points:
- By default members of classes are Private.
- By default classes are Internal.
- By default namespaces are Public but we are not supposed to specify the public keyword.
Access Specifier are as follows.
1. Private: Members can be accessed within the class only.
Example
- namespace Sample
- {
-
- public class ABC
- {
- private int Id;
- }
-
- public class Program
- {
- public static void Main(string[] args)
- {
- ABC abc = new ABC();
- abc.Id = 10;
- }
- }
- }
Output
Error 1 "Sample.ABC.Id" is inaccessible due to its protection level
2. Public: As the name says, members can be accessed from any class and any assembly.
3. Protected: Members can be accessed within its class and derived class of the same assembly.
Protected members are also accessible outside the assembly provided it should be derived.
Example 1
- namespace Sample
- {
-
- public class ABC
- {
- protected int Id;
- }
-
- public class Program
- {
- public static void Main(string[] args)
- {
- ABC abc = new ABC();
- abc.Id = 10;
- }
- }
-
- }
Output
Example 2
- namespace Sample
- {
-
- public class ABC
- {
- protected int Id;
- }
- public class XYZ : ABC
- {
- public void Print()
- {
- Id = 5;
- Console.WriteLine(Id);
- }
- }
- public class Program
- {
- public static void Main(string[] args)
- {
- XYZ xyz = new XYZ();
- xyz.Print();
- Console.ReadLine();
- }
-
- }
Output
4. Internal: Members can be accessed from anywhere within the same assembly.
Create a Class library
- namespace ClassLibrary1
- {
- public class Class1
- {
- internal int a;
- }
- }
Now create a console application, take a reference of the preceding library.
- namespace Sample
- {
- public class Program
- {
- public static void Main(string[] args)
- {
- ClassLibrary1.Class1 cls = new Class1();
- cls.a = 6;
- }
- }
- }
Output
Error 1 'ClassLibrary1.Class1' does not contain a definition for 'a' and no extension method 'a' accepting a first argument of type 'ClassLibrary1.Class1' could be found (are you missing a using directive or an assembly reference?
5. Protected Internal: Members can be accessed anywhere in the same assembly and also accessible by inheriting that class. It can be accessible outside the assembly in the derived class only. Protected Internal member works as Internal within the same assembly and works as Protected outside the assembly.
- namespace ClassLibrary1
- {
- public class Class1
- {
- protected internal int a;
- }
- }
Now create a console application and make a reference of the preceding library.
- namespace Sample
- {
-
- public class ABC:Class1
- {
- private int Id;
- public void XYZ()
- {
- a = 5;
- Console.WriteLine(a);
- }
- }
-
- public class Program
- {
- public static void Main(string[] args)
- {
- ABC abc = new ABC();
- abc.XYZ();
- Console.ReadKey();
-
-
- }
- }
- }