70. Protected access modifier#

Imagine a treasure chest, locked securely in a castle. It’s filled with gems and gold coins that should be available only to the royal family within the castle walls, and not to everyone else. This is essentially how the protected access modifier works. It allows us to make a member public within an inheritance hierarchy, but private to everyone else.

Key point

The protected access modifier allows a member to be accessed by the containing class or types derived from that class. This means that it restricts access to the family of the class, not just the class itself.

We’ve already met the public and private keywords in the chapter on access modifiers. Public members are like if the treasure chest was open waiting for anyone to take what they want. Private members, on the other hand, are more like if the treasure was only available to the king and only the king.

But what if we have a class that’s meant to be a base class and we want its fields or methods to be used by the classes that inherit from it? private is too restrictive because it doesn’t allow access by derived classes, and public is too permissive because it allows access by any class. This is where the protected access modifier comes in.

Hint

  • public means accessible by anyone.

  • private means accessible only from within the class itself.

  • protected means accessible only from within the class itself and any of its subclasses.

Let’s consider a simple example:

public class Animal
{
    protected string name = "Unnamed";

    public void SetName (string name)
        => this.name = name;
}
public class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine($"Woof, my name is {name}!");
    }
}

In this example, name is a protected field in the Animal class. This means it can be accessed by the Dog class, which is derived from Animal. The Bark method in the Dog class can access and use the name field directly.

Dog dog = new Dog();
dog.Bark();
Woof, my name is Unnamed!

However, if we were to try to access name from a class that is not derived from Animal, we would get a compiler error.

Animal animal = new Animal();
Console.WriteLine(animal.name);
(2,26): error CS0122: 'Animal.name' is inaccessible due to its protection level

The access modifier protected allows us to implement a common, controlled interface for base classes, while still providing the flexibility for derived classes to use and override those base class members.

Note

Remember the spirit of object oriented programming: encapsulate what varies and protect the integrity of your objects. The protected modifier can help you gain a little flexibility without fully giving up encapsulation.