Sobes.tech
Junior — Middle

Explain what the 'protected' access modifier means in a programming language and how it is used in classes.

sobes.tech AI

Answer from AI

The access modifier protected in C# means that a class member is accessible:

  • Within the class itself,
  • In derived classes (inheritants), even if they are in a different namespace or assembly.

However, unlike public, protected does not allow access to the member from other classes that are not inheritors.

Example of usage:

class BaseClass
{
    protected int protectedValue = 10;
}

class DerivedClass : BaseClass
{
    public void ShowValue()
    {
        Console.WriteLine(protectedValue); // Access is allowed
    }
}

class OtherClass
{
    public void TryAccess()
    {
        BaseClass obj = new BaseClass();
        // Console.WriteLine(obj.protectedValue); // Compilation error: no access
    }
}

Thus, protected helps restrict access to class members, allowing their use only within the inheritance hierarchy.

Explain what the 'protected' access modifier means in… - sobes.tech