C# Access Modifiers
Controlling access to class members.
C# Access Modifiers
Access modifiers are used to set the visibility level for classes, fields, methods and properties.
The most common access modifiers in C# are:
public: The code is accessible for all classesprivate: The code is only accessible within the same classprotected: The code is accessible within the same class, or in a class that is inherited from that class. You will learn more about inheritance in a later chapterinternal: The code is only accessible within its own assembly, but not from another assembly. You will learn more about this in a later chapter
By default, all members of a class are private if you don't specify an access modifier:
Examples
Public vs Private
Private members cannot be accessed directly.
using System;
class Car
{
public string model = "Mustang";
private string year = "1969";
public void DisplayInfo() {
// private members can be accessed here
Console.WriteLine(model + " " + year);
}
}
class Program
{
static void Main(string[] args)
{
Car myCar = new Car();
Console.WriteLine(myCar.model); // Allowed
// Console.WriteLine(myCar.year); // Error: Inaccessible
myCar.DisplayInfo(); // Allowed
}
}