Lesson 32 +10 XP

Access Modifiers

Access Modifiers

Access modifiers control who can use a class, field, or method. They are the heart of encapsulation.

The modifiers

ModifierAccess
publicaccessible everywhere
privateonly inside the same class
protectedsame class + derived classes
internalsame assembly (project)
public class Car
{
  public string color;
  private int price;
  protected int year;
}

private by default

Members are private if you don't write a modifier. That means a string color = "red"; field is private unless you mark it public.

public

public members are open to all other classes:

class Car
{
  public string model = "Mustang";
}

Car myCar = new Car();
Console.WriteLine(myCar.model);   // OK, public

private

private members only work inside their own class:

class Car
{
  private string model = "Mustang";
}

// Outside the class, myCar.model would be an error

Why encapsulate?

  • Protect data from accidental misuse.
  • Change the inside of a class without breaking others.
  • Expose only what should be public via properties (next lesson).

TL;DR

  • public - everywhere; private - only the class.
  • protected - class and subclasses; internal - same project.
  • Members are private by default.
  • Access modifiers enable encapsulation.