Accessibility Domain (C# Reference)
The accessibility domain of a member specifies where, in the program sections, a member can be referenced. If the member is nested within another type, its accessibility domain is determined by both the accessibility level of the member and the accessibility domain of the immediately containing type.
The accessibility domain of a top-level type is at least the program text of the project in which it is declared. That is, the entire source files of this project. The accessibility domain of a nested type is at least the program text of the type in which it is declared. That is, the type body, including any nested types. The accessibility domain of a nested type never exceeds that of the containing type. These concepts are demonstrated in the following example.
Example
This example contains a top-level type, T1
, and two nested classes, M1
and M2
. The classes contain fields with different declared accessibilities. In the Main
method, a comment follows each statement to indicate the accessibility domain of each member. Notice that the statements that attempt to reference the inaccessible members are commented out. If you want to see the compiler errors caused by referencing an inaccessible member, remove the comments one at a time.
// cs_Accessibility_Domain.cs
using System;
namespace AccessibilityDomainNamespace
{
public class T1
{
public static int publicInt;
internal static int internalInt;
private static int privateInt = 0; // CS0414
public class M1
{
public static int publicInt;
internal static int internalInt;
private static int privateInt = 0; // CS0414
}
private class M2
{
public static int publicInt = 0;
internal static int internalInt = 0;
private static int privateInt = 0; // CS0414
}
}
class MainClass
{
static void Main()
{
// Access is unlimited:
T1.publicInt = 1;
// Accessible only in current assembly:
T1.internalInt = 2;
// Error: inaccessible outside T1:
// T1.myPrivateInt = 3;
// Access is unlimited:
T1.M1.publicInt = 1;
// Accessible only in current assembly:
T1.M1.internalInt = 2;
// Error: inaccessible outside M1:
// T1.M1.myPrivateInt = 3;
// Error: inaccessible outside T1:
// T1.M2.myPublicInt = 1;
// Error: inaccessible outside T1:
// T1.M2.myInternalInt = 2;
// Error: inaccessible outside M2:
// T1.M2.myPrivateInt = 3;
}
}
}
C# Language Specification
For more information, see the following sections in the C# Language Specification:
3.5.1 Declared Accessibility
3.5.2 Accessibility Domains
3.5.4 Accessibility constraints
10.2.3 Access Modifiers
10.2.6.2 Declared Accessibility
See Also
Reference
C# Keywords
Access Modifiers (C# Reference)
Accessibility Levels (C# Reference)
Restrictions on Using Accessibility Levels (C# Reference)
Access Modifiers (C# Programming Guide)
public (C# Reference)
private (C# Reference)
protected (C# Reference)
internal (C# Reference)