Access Modifiers in C# Programming
28 March 2022
|
Viewed 2528 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 Modifier | Accessibility 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
// 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
| public | protected internal | protected | internal | private protected | private |
Within the class | Yes | Yes | Yes | Yes | Yes | Yes |
Derived class (same assembly) | Yes | Yes | Yes | Yes | Yes | No |
Non-derived class (same assembly) | Yes | Yes | No | Yes | No | No |
Derived class (different assembly) | Yes | Yes | Yes | No | No | No |
Non-derived class (different assembly) | Yes | No | No | No | No | No |
PreviousNext