Visibility and Accessibility Modifiers

Protected Access Modifier

The protected modifier is a special access modifier used in inheritance scenarios.

using System; public class Animal ...

 

The protected modifier marks a type member as available only in the type in which it is declared, or in any type that inherits from it.

public class Dog : Animal
{
    public void MakeSound()
    {
        Console.WriteLine(GetSound());
    }   
}

In the above example, the GetSound method can only be called from either the Animal class, or the Dog class.

You can also apply the protected modifier to a constructor, which effectively stops your class from being instantiated from anything but a class that inherits from it.

public class Dog : Animal
{

}

public class Animal
{
    // This protected constructor means that only inherited callers
    // create instances of Animal
    protected Animal()
    {

    }
}

 

Page 6 of 18