Glossary / Access modifiers

Access modifiers

Access modifiers control which code can access types and members. They form part of API design and encapsulation, limiting accidental coupling while allowing intended collaboration across classes, derived types, nested types, assemblies, and friend assemblies.

Accessibility levels

public is broadly accessible; private is limited to the containing type; protected allows the containing type and derived types; internal limits access to the current assembly; protected internal means same assembly or derived type; private protected means derived types within the same assembly. Top-level types generally support public or internal; nested types can use the full set. Default accessibility varies by declaration kind, so specify intentionally for public APIs.

The effective accessibility of a member cannot exceed that of its containing type or parameter/return types. InternalsVisibleTo grants a named friend assembly access to internals and can be useful for tests, but strong-name considerations apply. file-local types introduced in C# 11 are scoped to one source file, primarily to prevent generated/source types from colliding.

Design guidance

Keep public surfaces small and stable. Prefer private by default, expose capability through interfaces, and use protected carefully because it creates a subclass contract. internal is a useful assembly boundary but not a security sandbox. Access modifiers restrict compile-time access; reflection, unsafe code, and runtime trust boundaries require separate security analysis.

Interview questions

  1. protected internal meaning? Accessible from the same assembly or from derived types elsewhere.
  2. private protected meaning? Accessible by derived types in the same assembly.
  3. Is internal a security boundary? No; it is a language/assembly access boundary.
  4. Why limit protected members? They become extension points that constrain future implementation changes.
  5. What is file-local type? A type visible only within the source file where declared.

References