What are the access modifiers in C#?
Quick Answer
public — anywhere. private — only the containing type (default for class members). protected — the type and its subclasses. internal — the same assembly (default for top-level types). protected internal — subclasses OR same assembly. private protected — subclasses within the same assembly. file (C# 11) — the same file.
public is visible everywhere, private only inside the same type and it's the default for members, protected adds subclasses, and internal means the whole assembly and it's the default for top-level types. Then there are the combinations: protected internal is subclasses or same assembly, and private protected is subclasses that are also in the same assembly. My habit is to use the tightest one that compiles, so the public API stays small and I can refactor internals freely. For tests I use InternalsVisibleTo rather than making things public.
- Default for a class/struct/interface at namespace level is
internal; default for members isprivate. - Favour the most restrictive modifier that works — it keeps the public surface small and refactoring safe.
internal+[InternalsVisibleTo("MyProject.Tests")]lets a test project see internals without making them public.- Properties can have split accessibility:
public int Count { get; private set; }.