Sobes.tech
Junior — Middle

What role do access modifiers play in controlling the visibility of class members?

sobes.tech AI

Answer from AI

Access modifiers determine which parts of the code can see and use certain class elements (fields, methods, properties). This is an important encapsulation mechanism that helps control access to the internal data and logic of a class, ensuring security and preventing misuse.

Main access modifiers:

  • public — accessible everywhere, visible everywhere.
  • private — accessible only within the class itself.
  • protected — accessible within the class and its subclasses.
  • internal (in C#) — accessible within the current assembly (project).
  • protected internal — accessible within the assembly and to subclasses.

For example, if a field is made private, it will not be accessible from outside, which allows it to be modified only through class methods, controlling the logic of modification.

Example in C#:

class Person
{
    private string name; // not accessible from outside

    public void SetName(string newName)
    {
        if (!string.IsNullOrEmpty(newName))
            name = newName;
    }

    public string GetName() => name;
}