Access Modifiers
To promote encapsulation, a type or type member may hide itself from other types or other assemblies, by adding one of the following five access modifiers to the declaration:
-
public
The type or type member is fully accessible. This is the implicit accessibility for enum members (see Section 2.12) and interface members (see Section 2.10).
-
internal
The type or type member in assembly
A
is accessible only from withinA
. This is the default accessibility for nonnested types, so may be omitted.-
private
The type member in type
T
is accessible only from withinT
. This is the default accessibility for class and struct members, so it may be omitted.-
protected
The type member in class
C
is accessible only from withinC
or from within a class that derives fromC
.-
protected
internal
The type member in class
C
and assemblyA
is accessible only from withinC
, from within a class that derives fromC
, or from withinA
. Note that C# has no concept ofprotected
andinternal
, where a type member in classC
and assemblyA
is accessible only from withinC
or from within a class that derives fromC
and is withinA
.
Note that a type member may be a nested type. Here is an example that uses access modifiers:
// Assembly1.dll using System; public class A { private int x=5; public void Foo( ) {Console.WriteLine (x);} protected static void Goo( ) {} protected internal class NestedType {} } internal class B { private void Hoo ( ) { A a1 = new A ( ); // ok Console.WriteLine(a1.x); // error, ...
Get C# Essentials now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.