C# Access Modifiers
Access modifiers control the visibility of classes, methods, and fields — determining what other code is allowed to access them. Common modifiers are public, private, protected, and internal.
Using access modifiers correctly supports encapsulation, one of the core principles of OOP, by hiding internal details and exposing only what's necessary.
public type member;
private type member;
protected type member;public and private
public members can be accessed from any code, while private members can only be accessed from within the same class. private is the default for class members if no modifier is specified.
protected and internal
protected members are accessible within the class and its derived classes. internal members are accessible only within the same assembly (project).
using System;
class BankAccount {
private double balance = 100;
public double GetBalance() {
return balance;
}
}
class Program {
static void Main() {
BankAccount acc = new BankAccount();
Console.WriteLine(acc.GetBalance());
}
}100balance is private and only accessible via the public GetBalance() method.
using System;
class Animal {
protected string sound = "generic sound";
}
class Dog : Animal {
public void MakeSound() {
Console.WriteLine(sound);
}
}
class Program {
static void Main() {
Dog d = new Dog();
d.MakeSound();
}
}generic soundprotected allows the derived class Dog to access the sound field from Animal.
Key points
- public members are accessible from anywhere.
- private members are accessible only within the same class.
- protected members are accessible in the class and its subclasses.
- internal members are accessible only within the same assembly.
