What are Access Specifiers & Access Modifiers in C#?
Access Specifiers (Access Modifiers) are keywords in Object Oriented Programming that specify the 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 Specifiers are as follows.
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; // Error, Id is private
}
}
}
Output
Public
As the name says, members can be accessed from any class and any assembly.
Protected
Members can be accessed within their class and derived class of the same assembly.
tested members are also accessible outside the assembly, provided it should be derived.
namespace Sample
{
public class ABC
{
protected int Id;
}
public class Program
{
public static void Main(string[] args)
{
ABC abc = new ABC();
abc.Id = 10;//error ,its protected
}
}
}
Output
Example
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
Internal
Members can be accessed from anywhere within the same assembly.
Create class library
namespace ClassLibrary1
{
public class Class1
{
internal int a;
}
}
Now create a console application, and take a reference of the preceding library.
namespace Sample
{
public class Program
{
public static void Main(string[] args)
{
ClassLibrary1.Class1 cls = new ClassLibrary1.Class1();
cls.a = 6; // error
}
}
}
Output
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 to the preceding library.
using System;
namespace Sample
{
public class Class1
{
protected internal int a;
}
public class ABC : Class1
{
private int Id;
public ABC()
{
a = 5;
}
public void XYZ()
{
Console.WriteLine(a);
}
}
public class Program
{
public static void Main(string[] args)
{
ABC abc = new ABC();
abc.XYZ();
Console.ReadKey();
}
}
}