Skip to content

Access Modifiers

Overview

Access modifiers control the visibility of types, fields, methods, and properties:

ModifierVisibility
publicAccessible from anywhere
privateAccessible only within the declaring type
protectedAccessible within the declaring type and subtypes
internalAccessible 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

DeclarationDefault
Top-level types, functions, enumsinternal
Type fieldspublic
Type methodspublic
Type propertiespublic
Type constructorspublic
public type PublicApi { }
internal type InternalHelper { }