Complete C# Tutorial

Understanding C# Protected Access Specifiers with Examples

Introduction

Imagine you have a secret recipe 📝 for your grandma’s delicious cookies 🍪. You don’t want the whole world to know it, but you’d love to pass it down to your kids. That means the recipe should stay within the family.

That’s exactly how C# Protected Access Specifiers work! They allow access within a class and its child (derived) classes, but no outsiders can touch it.

Sounds interesting? Let’s break it down! 😃

What are Protected Access Specifiers in C#?

A protected member is like a family secret—only the class itself and its children (derived classes) can access it.

Key points:

🔹 Declared using the protected keyword.
🔹 Accessible in the same class and in derived (child) classes.
🔹 Not accessible outside the class hierarchy.

Syntax

				
					protected dataType variableName;

protected returnType MethodName()  
{  
    // Code inside  
}
				
			

It’s as simple as adding the protected keyword before a variable or method! 🙌

Simple Example to Understand Protected Access

				
					using System;

class Animal
{
    protected string name;  // Protected variable

    public void SetName(string animalName)
    {
        name = animalName;  // Can be accessed inside this class
    }
}

// Dog is inheriting from Animal
class Dog : Animal
{
    public void ShowName()
    {
        Console.WriteLine("Dog's Name: " + name);  // Can access 'name' inside derived class
    }
}

class Program
{
    static void Main()
    {
        Dog myDog = new Dog();
        myDog.SetName("Buddy");  // Setting name using public method
        myDog.ShowName();        // Displaying name using protected access

        // myDog.name = "Max";  // ❌ Error! 'name' is protected and can't be accessed directly.
    }
}
				
			

Output

				
					Dog's Name: Buddy
				
			

Code and Output Explanation

Alright, let’s go step by step! 📝

  • We created an Animal class with a protected variable name.
  • SetName is a public method that assigns a value to name.
  • The Dog class inherits from Animal, so it can access name inside the ShowName method.
  • In Main, we created a Dog object, set its name, and displayed it.
  • If we try to access name directly outside the class, C# yells at us! 🚫

The magic? ✨ The protected variable is hidden from outsiders but is available inside child classes.

Real-World Example: Employee System 🏢

Imagine a company where every employee has a salary. This salary should not be changed directly, but a manager (who is also an employee) should be able to see it. Let’s code that!

				
					using System;

class Employee
{
    protected double salary;  // Protected variable

    public void SetSalary(double amount)
    {
        if (amount > 0)
        {
            salary = amount;
        }
        else
        {
            Console.WriteLine("Invalid salary amount!");
        }
    }
}

class Manager : Employee
{
    public void ShowSalary()
    {
        Console.WriteLine($"Manager's Salary: ${salary}");  // Accessing protected variable
    }
}

class Program
{
    static void Main()
    {
        Manager manager = new Manager();
        manager.SetSalary(5000);  // Setting salary
        manager.ShowSalary();      // Displaying salary

        // manager.salary = 10000;  // ❌ Error! 'salary' is protected.
    }
}
				
			

Output

				
					Manager's Salary: $5000
				
			

Breaking Down the Real-World Example

  • The Employee class has a protected salary variable.
  • The SetSalary method ensures salaries are set properly.
  • The Manager class inherits from Employee, so it can access salary inside ShowSalary.
  • In Main, we created a Manager object, set a salary, and displayed it.
  • Protected saved the day! No one outside the class hierarchy can mess with salary.

Real-world security in action! 🔥

Conclusion

So, what did we learn today? 🤔

C# Protected Access Specifiers are like family secrets—they stay within the class and its children. They provide controlled access, making sure only the right people can use them.

When should you use protected? Whenever you want child classes to have access to something but keep it hidden from outsiders. Pretty handy, right? 😃

Next what?

Boom! 💥 You just mastered C# Protected Access Specifiers! Feeling like a pro? You should! 😎

Next up, we’ll dive into Internal Access Specifiers in C#. It’s another cool way to control access in your code. Don’t miss it! 🚀

Leave a Comment

Share this Doc

Protected

Or copy link