![]() |
VOOZH | about |
Access modifiers in C# define the scope and visibility of classes, methods, fields, constructors and other members. They determine where and how a member can be accessed in a program.
There are 6 access modifiers (public, protected, internal, private, protected internal, private protected) as follows:
Modifiers | Entire program | Containing Class | Current assembly | Derived Types | Derived Types within Current Assembly |
|---|---|---|---|---|---|
public | Yes | Yes | Yes | Yes | Yes |
private | No | Yes | No | No | No |
protected | No | Yes | No | Yes | Yes |
internal | No | Yes | Yes | No | Yes |
protected internal | No | Yes | Yes | Yes | Yes |
private protected | No | Yes | No | No | Yes |
Accessible from anywhere in the project or other assemblies (if referenced). public is suitable for members that need to be globally available. Example:
Displaying using class members Roll number: 1 Name: Geek Displaying Using methods Roll number: 1 Name: Geek
When we use private modifier, member is accessible only within the same class. Default modifier for class members if none is specified is private. It It is used for encapsulation of data. Example:
Value = 4
protected access modifier allows members to be accessible within the class and by derived classes (subclasses). It does not allow access from outside the class or its derived classes. Example:
The student's name is: Geeky
Accessible only within the same assembly (project). Not visible to other assemblies unless explicitly exposed with InternalsVisibleTo. Example:
Real = 2 Imaginary = 1
It is the combination of protected and internal. Members are accessible within the same assembly and also by derived classes (even if they are in a different assembly). Example:
Hello from Parent!
private protected access is only granted to the containing class. Any other class inside the current or another assembly is not granted access to these members. This modifier is valid in C# version 7.2 and later. Example:
Output:
Value = 4