Access Modifiers in C# Programming

28 March 2022 | Viewed 2066 times

What is an Access Modifier?

In Object oriented Programming, all types and type members have an accessibility levels. The accessibility level controls whether they can be used from other code in your assembly or other assemblies. To define these accessibility level we will use access modifiers.

Default access modifier for Class is "Internal". Default access modifier for Data Member and Member Function of Class is "Private".
List of Access Modifiers
Access ModifierAccessibility Level
public can be accessed by any other code in the same assembly or another assembly that references it.
private can be accessed only by code in the same class or struct.
protected can be accessed only by code in the same class, or in a class that is derived from that class.
internal can be accessed by any code in the same assembly, but not from another assembly.
protected internal can be accessed by any code in the assembly in which it's declared, or from within a derived class in another assembly.
private protected can be accessed by types derived from the class that are declared within its containing assembly.

Sample C# Code

C# Code
// public class:
public class Employee
{
// protected method:
protected void Age() { }

// private field:
private int employeeId = 100;

// protected internal property:
protected internal int EmployeeId
{
get { return employeeId; }
}
}


Access Modifiers and its scope
publicprotected internalprotectedinternalprivate protectedprivate
Within the classYesYesYesYesYesYes
Derived class (same assembly)YesYesYesYesYesNo
Non-derived class (same assembly)YesYesNoYesNoNo
Derived class (different assembly)YesYesYesNoNoNo
Non-derived class (different assembly)YesNoNoNoNoNo

PreviousNext