Access Modifiers
Overview
Access modifiers control the visibility of types, fields, methods, and properties:
| Modifier | Visibility |
|---|---|
public | Accessible from anywhere |
private | Accessible only within the declaring type |
protected | Accessible within the declaring type and subtypes |
internal | Accessible within the same module |
Per-Member Prefix
Apply a modifier directly before each member:
type Account{ private float balance; public string owner;
public void Deposit(float amount) { balance = balance + amount; }
public float GetBalance() this.balance;}Members without an explicit modifier default to public.
Section-Style Modifiers
Group members under a visibility section with a colon:
type Parser{ private: int pos = 0; string source;
char Peek() this.source[this.pos]; void Advance() { this.pos = this.pos + 1; }
public: int Parse() { // uses Peek/Advance internally return 0; }}Protected
protected members are accessible to subclasses:
type Animal{ protected string name; protected string MakeSound() "...";
public void Speak() { Console.WriteLine(name + " says: " + MakeSound()); }}
type Dog : Animal{ override string MakeSound() "Woof!";}Internal
internal members are visible across all types within the same module but hidden from external consumers:
internal type InternalCache{ string Get(string key) { return ""; }}Mixing Modifiers on Property Accessors
Property accessors can have different visibility:
type Box{ int Value { get; private =; }
void Init(int v) { this.Value = v; }}Default Access
| Declaration | Default |
|---|---|
| Top-level types, functions, enums | internal |
| Type fields | public |
| Type methods | public |
| Type properties | public |
| Type constructors | public |
public type PublicApi { }internal type InternalHelper { }