
Class and Struct Member Accessibility
Class members (including nested classes and structs) can be declared with any of the five types of access. Struct members cannot be declared as protected because structs do not support inheritance.
The accessibility of a member can never be greater than the accessibility of its containing type. For example, a public method declared in an internal type has only internal accessibility.
When a member of a class or struct is a property, field, method, event, or delegate, and that member either is a type or has a type as a parameter or return value, the accessibility of the member cannot be greater than the type. For example, you cannot have a public method M that returns a class C unless C is also public. Likewise, you cannot have a protected property of type A if A is declared as private.
User-defined operators must always be declared as public. For more information, see operator (C# Reference).
Destructors cannot have accessibility modifiers.
To set the access level for a class or struct member, add the appropriate keyword to the member declaration. Here are some examples:
// public class:
public class Tricycle
{
// protected method:
protected void Pedal() { }
// private field:
private int wheels = 3;
// protected internal property:
protected internal int Wheels
{
get { return wheels; }
}
}
Note: |
|---|
The
protected internal accessibility means protected OR internal, not protected AND internal. In other words, a protected internal member is accessible from any class in the same assembly, including derived classes. To limit accessibility to only derived classes in the same assembly, declare the class itself internal, and declare its members as protected.
|