These are also access specifiers used to define the scope of type and member functions. i.e., who can
access them and who cannot.
C# provides 5 access modifiers:
- Private
- Internal
- Protected
- Protected Internal
- Public
Members declared as private under a class or structure cannot be accessed outside of the
type and its scope only apply to that type in which it is defined.
Note: Interface cannot contain private members and the default scope of interface members is public.
Syntax:
// private class
private class
// private field
private
Eg: private int number= 10;
// private method
private
Eg: private void MethodA()
{
}
Members declared as Protected under a class can be accessed only within the class and
the derived class (child class). The other classes which are not derived ones cannot access the protected
members.
Syntax:
// protected class
protected class
// protected field
protected
Eg: protected int number= 10;
// protected method
protected
Eg: protected void MethodA()
{
}
Members and Types that are declared as Internal can be accessed only within the project.
The scope is at the project level so that child and non-child classes within the project can access the internal
members.
Syntax:
// internal class
internal class
// internal field
internal
Eg: internal int number= 10;
// internal method
internal
Eg: internal void MethodA()
{
}
Members declared as Protected Internal have dual scope features. It means
the members behave as “Internal “ within the project providing access to anywhere in project level and
behaving as “Protected” outside the project by providing access to child classes. So only members are
declared as Protected Internal, the types cannot be declared as Protected Internal.
Syntax:
// protected internal class
protected internal class
// protected internal field
protected internal
Eg: protected internal int number= 10;
// protected internal method
protected internal
Eg: protected internal void MethodA()
{
}
Members or Types declared as Public can be accessed from anywhere. It is global in scope.
Syntax:
// public class
public class
// public field
public
Eg: public int number= 10;
// public method
public
Eg: public void MethodA()
{
}
Case |
Private |
Protected |
Internal |
Protected Internal |
Public |
Scenario 1 |
Yes |
Yes |
Yes |
Yes |
Yes |
Scenario 2 |
No |
Yes |
Yes |
Yes |
Yes |
Scenario 3 |
No |
No |
Yes |
Yes |
Yes |
Scenario 4 |
No |
Yes |
No |
Yes |
Yes |
Scenario 5 |
No |
No |
No |
No |
Yes |
Scenario 1: Accessing the members of a class from the same class.
Scenario 2: Accessing the members of a class from the child class of the same project.
Scenario 3: Accessing the members of a class from the non-child class of the same project.
Scenario 4: Accessing the members of a class from the child class of another project.
Scenario 5: Accessing the members of a class from the non-child class of another project.