The protected access modifier lets a class share its members only with its own children (derived classes). It keeps things hidden from the outside world but open to family.
Protected access modifier in C Sharp (C#)
protected type memberName; protected returnType MethodName(parameters) { // method body }
protected members are accessible inside the class and in any class that inherits from it.
They are not accessible from outside these classes.
name. Only Animal and its children can access it.class Animal { protected string name; }
Speak method is protected, so only Animal and subclasses can call it.class Animal { protected void Speak() { Console.WriteLine("Animal sound"); } }
Dog class inherits from Animal and can call the protected Speak method.class Dog : Animal { public void Bark() { Speak(); // allowed because Speak is protected } }
This program shows a base class Animal with a protected field and method. The Dog class inherits from Animal and can use the protected method ShowName. Trying to call ShowName from outside the class family causes an error.
using System; class Animal { protected string name; public Animal(string name) { this.name = name; } protected void ShowName() { Console.WriteLine($"Animal name is {name}"); } } class Dog : Animal { public Dog(string name) : base(name) {} public void Display() { ShowName(); // Accessing protected method from base class } } class Program { static void Main() { Dog dog = new Dog("Buddy"); dog.Display(); // dog.ShowName(); // Error: ShowName is protected } }
Protected members are a way to share inside a family of classes but keep secrets from others.
Remember, protected members are not visible to objects of the class, only to the class code and subclasses.
Protected means only the class and its children can see or use the member.
It helps keep code safe but still flexible for extensions.
Use it when you want to share with subclasses but hide from the outside world.