Understanding C# Access Modifiers
Information hiding is essential in object oriented as well as in modular programming. C# provides the access modifiers private , internal , public , protected and protected internal to give a programmer fine grained control over the visibility of a member in a specific context. Those contexts are namespace , class , struct , interface and enum . A member would be e.g. a field, an event, a delegate, property or method. But, as Marc's table shows, this does not really matter. A member's context alone determines if a modifier can be applied at all (□), and which modifier is the default (■).
|
namespace |
class |
struct |
interface |
enum |
private |
|
■ |
■ |
|
|
internal |
■ |
□ |
□ |
|
|
public |
□ |
□ |
□ |
■* |
■* |
protected |
|
□ |
|
|
|
protected internal |
|
□ |
|
|
|
*) Because members of interface and enum are always public by default, the modifier must not be applied in those contexts.
The individual access modifiers are defined in the C# Language Specification as
private |
Access limited to the containing type |
internal |
Access limited to this program |
public |
Access not limited |
protected |
Access limited to the containing class or types derived from the containing class |
protected internal |
Access limited to this program or types derived from the containing class |
Note: the term this program can be replaced by the containing assembly.
|