Access Modifiers
To promote encapsulation, a type or type member may limit its accessibility to other types and other assemblies by adding one of five access modifiers to the declaration:
-
public
Fully accessible. The implicit accessibility for members of an enum or interface.
-
internal
Accessible only within containing assembly or friend assemblies. The default accessibility for nonnested types.
-
private
Visible only within containing type. The default accessibility members of a class or struct.
-
protected
Visible only within containing type or subclasses.
-
protected internal
The union of
protected
andinternal
accessibility. (This is less restrictive thanprotected
orinternal
alone.)
Note
The CLR has the concept of the intersection of protected and internal accessibility, but C# does not support this.
Examples
Class2
is accessible from outside its assembly;
Class1
is not:
class Class1 { } // Class1 is internal (default)
public
class Class2 { }
ClassB
exposes field x
to other types in the same assembly; ClassA
does not:
class ClassA { int x; } // x is private
// (default)
class ClassB { internal
int x; }
Functions within Subclass
can call Bar
but not Foo
:
class BaseClass
{
void Foo() { } // Foo is private (default)
protected
void Bar() { }
}
class Subclass : BaseClass
{
void Test1() { Foo(); } // Error: cannot access Foo
void Test2() { Bar(); } // OK
}
Accessibility Capping
A type caps the accessibility of its declared members. The most common example of
capping is when you have an internal ...
Get C# 3.0 Pocket Reference, 2nd Edition 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.