C# Access Modifiers: Controlling Class Member Visibility and Accessibility
Understand and master C#'s access modifiers (public, private, protected, internal, protected internal) for building well-structured and secure applications. This tutorial explains how access modifiers control member visibility, demonstrates their usage with code examples, and highlights their importance in creating robust and maintainable object-oriented designs.
Access Modifiers (Specifiers) in C#
Access modifiers in C# control the visibility and accessibility of class members (fields, methods, properties, etc.). They determine which parts of your code can access those members. Proper use of access modifiers is crucial for building well-structured, maintainable, and secure applications.
Types of Access Modifiers
C# provides five access modifiers:
Modifier | Accessibility |
---|---|
public |
Accessible from anywhere. |
protected |
Accessible only from within the class itself and from derived classes. |
internal |
Accessible only from within the same assembly (project). |
protected internal |
Accessible from within the same assembly or from derived classes in other assemblies. |
private |
Accessible only from within the class where it's declared. |
Examples: Demonstrating Access Levels
Let's illustrate each access modifier with examples. (Note: The "Test it Now" links would lead to executable code examples demonstrating the access level behavior in a real HTML page.)
1. `public` Access Modifier
Public members are completely unrestricted in terms of access. They can be accessed from any other code.
2. `protected` Access Modifier
Protected members are accessible only from within the class itself and from classes that inherit from it.
Example 1 (Compile-time error): Attempting to access a protected member from outside the class.
Example 2 (Successful Access): Accessing a protected member from a derived class.
3. `internal` Access Modifier
Internal members are only accessible from within the same assembly (project).
4. `protected internal` Access Modifier
`protected internal` members are accessible from within the same assembly or from derived classes in other assemblies. This combines the accessibility of `protected` and `internal`.
5. `private` Access Modifier
Private members are the most restricted. They are only accessible from within the class in which they are declared.
Example 1 (Compile-time error): Attempting to access a private member from outside the class.
Example 2 (Successful access): Accessing a private member from within the same class.