What is an access modifier?
Access modifiers are keywords in object-oriented languages that set the accessibility of classes, methods, and other members. Access modifiers are a specific part of programming language syntax used to facilitate the encapsulation of components.
Which are the access modifiers in C#?
There are 6 types of C# modifiers:
- public – Fully accessible.
- internal – Accessible only within the containing assembly or friend assemblies.
- private – Accessible only within the containing type.
- protected – Accessible only within the containing type or subclasses.
- protected internal – Accessible in two ways.
- private protected – Access is limited to the containing class or types derived from the containing class within the current assembly.
Examples:
ClassA is accessible only in current assembly; ClassB is accessible outside of assembly:
class ClassA {} // ClassA is internal (default)
public class ClassB {} // ClassB is public
In ClassA “y” is private by default, in ClassB “y” is internal so it is accessible only for this assembly; “x” is public but the class is internal by default so “x” is accessible only in this assembly.
class ClassA { int y; } // y is private (default) class ClassB { internal int y; public int x;} //y is internal and can be accsesible only in the current assembly //x is public, but the class is internal
Was this article helpful?
If you have any suggestions or questions, please leave a comment below.
Leave A Comment