C# Keywords Tutorial Part 66: protected

C# Keywords Tutorial Part 66: protected

Encapsulation, inheritance, and polymorphism are all features supported by the object-oriented programming language C#. “Protected” is one of the terms that is very important in inheritance. A derived class may access the members of its base class by using this keyword. In this blog article, we’ll talk about the C# term “protected” and look at some instances of how to use it.

An access modifier known as “protected” limits a member’s access to the base class and its derived classes. When we wish to make a member available only inside the class and any derived classes, but not outside of them, we utilize this technique. Here is an illustration to show this:

class Animal
{
    protected string name;
}
class Dog : Animal
{
    public void SetName(string name)
    {
        this.name = name;
    }
}
class Program
{
    static void Main(string[] args)
    {
        Dog myDog = new Dog();
        myDog.SetName("Fido");
        Console.WriteLine(myDog.name);
    }
}

Here, the base class “Animal” includes a protected string property called “name” that can only be used for this example. Then, a class called “Dog” that derives from “Animal” is created. Additionally, we have a method called “SetName” that modifies the “name” field’s value. In the “Dog” class, “name” is available, but not outside of it because it is a protected member.

We construct a “Dog” instance and give it the name “Fido” in the Main function. Next, we attempt to use the “myDog.name” expression to access the “name” field. We can access “name” within the “Dog” class and classes descended from it since it is a protected member. As a result, “Fido” will be the program’s output.

Let’s take another example to understand the usage of “protected” with methods:

class Vehicle
{
    protected void StartEngine()
    {
        Console.WriteLine("Starting engine...");
    }
}
class Car : Vehicle
{
    public void Start()
    {
        StartEngine();
    }
}
class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car();
        myCar.Start();
    }
}

In this example, we have a base class named “Vehicle” that has a protected method named “StartEngine”. We then have a derived class named “Car” that inherits from “Vehicle”. The “Car” class has a public method named “Start” that calls the “StartEngine” method. Since “StartEngine” is a protected method, it is accessible within the “Car” class and its derived classes.

In the Main method, we create an instance of “Car” and call its “Start” method. The “Start” method then calls the “StartEngine” method, which outputs “Starting engine…”. Since “StartEngine” is a protected method, we can call it within the “Car” class and its derived classes. Hence, the output of the program will be “Starting engine…”.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *