C# Access Modifiers
Access modifiers are keywords that control who is allowed to see and use your classes, fields, and methods. They are the foundation of encapsulation, one of the core ideas in object-oriented programming. In this lesson you will meet public, private, protected, and internal, and learn when to reach for each one.
Why access modifiers matter
When you build a class, some parts are meant for the outside world to use, while other parts are private helpers that should stay hidden. Access modifiers let you draw that line. Hiding the inner workings of a class is called encapsulation, and it makes your code safer and easier to change later.
- public - accessible from anywhere, inside or outside the class
- private - accessible only inside the same class
- protected - accessible inside the class and by classes that inherit from it
- internal - accessible only within the same project (assembly)
public vs private
class Account
{
public string owner; // anyone can read or change this
private double balance; // only Account code can touch this
public void Deposit(double amount)
{
balance = balance + amount; // allowed: same class
}
public double GetBalance()
{
return balance;
}
}
class Program
{
static void Main()
{
Account a = new Account();
a.owner = "Sam"; // OK: public
a.Deposit(100); // OK: public method
// a.balance = 999; // ERROR: balance is private
Console.WriteLine(a.GetBalance()); // 100
}
}By keeping balance private, we force everyone to go through Deposit and GetBalance. That means we can add rules later, such as refusing negative deposits, and no outside code can bypass them.
The default access level
If you do not write any access modifier on a class member, C# treats it as private. Because private is easy to forget, many teams write the modifier out explicitly on every member so the intent is always clear.
protected and inheritance
class Animal
{
protected string name = "Animal"; // visible to subclasses
}
class Dog : Animal
{
public void Introduce()
{
// allowed because Dog inherits from Animal
Console.WriteLine("I am a " + name);
}
}Where each modifier reaches
Exercise: C# Access Modifiers
If no access modifier is specified on a member of a C# class, what is applied by default?