Access modifiers in C# define the visibility and scope of classes, methods, variables, and other members. They help protect data and enforce encapsulation.
Modifier | Description |
---|---|
public |
Accessible from anywhere (inside or outside the class/project) |
private |
Accessible only within the same class |
protected |
Accessible within the class and by derived classes |
internal |
Accessible only within the same assembly (project) |
protected internal |
Accessible in the same assembly and from derived classes in other assemblies |
private protected |
Accessible within the same class and derived classes in the same assembly |
class Car
{
public string brand = "Toyota"; // Can be accessed from anywhere
private string model = "Fortuner"; // Can only be accessed inside Car
protected int speed = 100; // Accessible in derived classes
internal string fuel = "Diesel"; // Accessible only within this project
}
class SUV : Car
{
public void Display()
{
Console.WriteLine(brand); // ✅ Accessible (public)
// Console.WriteLine(model); ❌ Not accessible (private)
Console.WriteLine(speed); // ✅ Accessible (protected)
}
}
private
or protected
by default and increase visibility only when required. This keeps your code safe and maintainable.
public
: Everywhereprivate
: Inside the class onlyprotected
: Inside the class and its childreninternal
: Same assembly/projectprotected internal
: Same project + children in other projectsprivate protected
: Same class + derived in same projectHelp others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!