0
0
C Sharp (C#)programming~5 mins

Protected access modifier in C Sharp (C#)

Choose your learning style9 modes available
Introduction

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.

When you want to let child classes use or change a variable or method but keep it hidden from other classes.
When you build a base class and want to allow special behavior only in classes that extend it.
When you want to protect important data but still let subclasses access it safely.
When you want to organize code so only related classes can see certain details.
Syntax
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.

Examples
This class has a protected field name. Only Animal and its children can access it.
C Sharp (C#)
class Animal {
    protected string name;
}
The Speak method is protected, so only Animal and subclasses can call it.
C Sharp (C#)
class Animal {
    protected void Speak() {
        Console.WriteLine("Animal sound");
    }
}
The Dog class inherits from Animal and can call the protected Speak method.
C Sharp (C#)
class Dog : Animal {
    public void Bark() {
        Speak(); // allowed because Speak is protected
    }
}
Sample Program

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.

C Sharp (C#)
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
    }
}
OutputSuccess
Important Notes

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.

Summary

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.