Access Modifiers in C# (protected)

January2, 2018
by admin

Till now we have seen ‘public’, ‘private’ and ‘internal’ access modifiers with demo examples. Let’s see in this section another important access modifier ‘protected’.

If you have not read the previous articles on access modifiers yet, it is highly recommended to read them first before reading this one. Click below links to read those articles.

Access Modifiers in C# (public, private)

Access Modifiers in C# (internal)

For the demonstration let’s use our existing project ‘AccessModifierDemo’ and do some code changes.

Let’s first look at the existing project structure shown in the following image.

Open the ‘Employee’ class from ’EmployeeInfo’ project and make the changes as per code shown below. Please note that the changes are in bold font.


namespace EmployeeInfo
{
  public class Employee
  {
    private string _firstName;
    private string _lastName;

    public string FirstName
    {
      get
      {
        return _firstName;
      }
      set
      {
        _firstName = value;
      }
    }

    public string LastName
    {
      get
      {
        return _lastName;
      }
      set
      {
        _lastName = value;
      }
    }

    protected void PrintEmployeeInfo()
    {
      Console.WriteLine(string.Format("Name: {0} {1}", _firstName, _lastName));
    }
  }
}

The only change we have done in this class is that we are now assigning ‘protected’ access modifier to ‘PrintEmployeeInfo()’ method instead of ‘internal’.

With this small change, the accessibility level of ‘PrintEmployeeInfo()’ method changed.

With ’protected’ access modifier, a member can be accessible to all members of its own class and all members of inherited classes. An Inherited class may belong to the same project or it may belong to a different project.

To other classes of any projects, this member is not accessible.

Let’s create a new class ‘EmployeeProfile’ in ‘EmployeeInfo’ project.

Right click on ‘EmployeeInfo’ project and click ‘Add > Class’ menu item.

Change the name of the class as ‘EmployeeProfile’ and click ’Add’ button. This will create a class file ‘EmployeeProfile.cs’.

Add the following code to ‘EmployeeProfile’ class.


namespace EmployeeInfo
{
  public class EmployeeProfile: Employee
  {
    private string _designation;

    public string Designation
    {
      get
      {
        return _designation;
      }
      set
      {
        _designation = value;
      }
    }

    public void PrintProfileInfo()
    {
      PrintEmployeeInfo();
      Console.WriteLine(string.Format("Designation: {0}", _designation));
    }
  }
}

The things to point out here are as follows.

We have added the ’Designation’ property to store and retrieve employee’s designation.

Also, a ’PrintProfileInfo()’ method is for printing employees information such as name and designation.

The ’EmployeeProfile’ class is inherited from ’Employee’ class and thus it has access to protected members of it. So ‘PrintEmployeeInfo()’ method is called in ’PrintProfileInfo()’ method to print the employee’s name to console window. This ‘PrintProfileInfo()’ method also prints the employee’s designation as output.

That’s all we have to do in ‘EmployeeInfo’ project.

Now let’s open our main project ‘AccessModifierDemo’.

Replace the existing code within the Main() function of ‘Program’ class with the following code.


using EmployeeInfo;

namespace AccessModifierDemo
{
  class Program
  {
    static void Main(string[] args)
    {
      EmployeeProfile employeeProfile = new EmployeeProfile();

      employeeProfile.FirstName = "Chittaranjan";
      employeeProfile.LastName = "Dhurat";
      employeeProfile.Designation = "Software Programmer";

      employeeProfile.PrintProfileInfo();
      
      Console.ReadKey();
    }
  }
}

Let’ go through the code.

We have already created a reference to the ‘EmployeeInfo’ project in ‘AccessModifierDemo’ project.

We have given a reference to the ’EmployeeInfo’ namespace using ’using’ statement at the top of the ’Program’ class.

using EmployeeInfo;

Within the ‘Main’ function, we have created an object of ‘EmployeeProfile’ class.

EmployeeProfile employeeProfile = new EmployeeProfile();

Then we have assigned the values for employee’s first name, last name, and designation. FirstName and LastName are public properties of EmployeeProfile’s base class ‘Employee’. So it has access to it and Designation is its own property.

employeeProfile.FirstName = "Chittaranjan";
employeeProfile.LastName = "Dhurat";
employeeProfile.Designation = "Software Programmer";

Next, we have called ‘PrintProfileInfo()’ method to print employees information to console output.

employeeProfile.PrintProfileInfo();

The thing to remember here is that this ‘PrintProfileInfo()’ method internally called ‘PrintEmployeeInfo()’ method of its base class ‘Employee’ to print first name and last name of the employee.

If we try to call this method by creating an object of ‘Employee’ class in Main() function it will fail as shown in the following code.

Employee employee = new Employee();
employee.FirstName = "Chittaranjan";
employee.LastName = "Dhurat";
employee.PrintEmployeeInfo();    // This is not allowed due to ‘protected’ level.

The above code of creating object of ‘Employee’ class and then calling ‘PrintEmployeeInfo()’ method will not work since ‘PrintEmployeeInfo()’ method has ‘protected’ access modifier and it is only accessible to its inherited class members (‘EmployeeProfile’ class) and not to any other class members (‘Program’ class).

Once we call the ‘PrintProfileInfo()’ method of ‘EmployeeProfile’ object we have just called the Console.ReadKey() method so that user can see or observe the result on console output window and press any key to terminate the application.

Now save the solution , and run the application by pressing key ‘F5’. We will get the following output.

Output:

Name: Chittaranjan Dhurat
Designation: Software Programmer

So far we have seen how any class member with ‘protected’ access modifier can only be accessible to inherited class members in the same project.

Now the question is whether it is accessible to class members of any other project or not? The answer is for any other project also it is accessible to members of inherited class only.

In our example, we have defined protected member ‘PrintEmployeeInfo()’ in Employee class which resides in ‘EmployeeInfo’ project.

Our main console application project ‘AccessModifierDemo’ has reference to ‘EmployeeInfo’ project.

Since ’PrintEmployeeInfo()’ method of Employee class has ’protected’ access modifier, we can’t access it by an object of Employee class.

But if we create any class inherited from ’Employee’ class, then that class members can have access to protected ’PrintEmployeeInfo()’ method.

Suppose, we have a requirement to store and print employees category along with his name then we can create ‘EmployeeCategory’ class in ‘AccessModifierDemo’ project and inherit it from ‘Employee’ class so that it can have access to protected method ‘PrintEmployeeInfo()’ of ‘Employee’ base class.

Let’s see this with coding.

First open ‘AccessModifierDemo’ project.

Create a new class ‘EmployeeCategory’.

Right click on ‘AccessModifierDemo’ project and click ‘Add > Class’ menu item.

Change the name of the class as ‘EmployeeCategory’ and click ’Add’ button. This will create a class file ‘EmployeeCategory.cs’.

Inherit ‘EmployeeCategory’ class from ‘Employee’ class.

Write the following code.


using EmployeeInfo;

namespace AccessModifierDemo
{
  public class EmployeeCategory: Employee
  {
    public string Category { get; set; }

    public void PrintEmployeeCategory()
    {
      PrintEmployeeInfo();
      Console.WriteLine(string.Format("Category: {0}", Category));
    }
  }
}

Let’s go through above code.

We have first defined ‘Category’ property of type ‘string’ for employee category. Note that this an automatic property.

Then we have written ’PrintEmployeeCategory()’ method. This method prints employee category along with his name.

To print employee name we have just called PrintEmployeeInfo() method from base ‘Employee’ class. Then we have printed the employee’s category to console window.

Save the file by pressing the key (Ctrl + S).

Now open ‘Program’ class and replace existing code with the following one.


namespace AccessModifierDemo
{
  class Program
  {
    static void Main(string[] args)
    {
      EmployeeCategory employeeCategory = new EmployeeCategory();

      employeeCategory.FirstName = "Chittaranjan";
      employeeCategory.LastName = "Dhurat";
      employeeCategory.Category = "Senior level";

      employeeCategory.PrintEmployeeCategory();

      Console.ReadKey();
    }
  }
}

Let’s go through the code.

On the first line, we have created an object of ‘EmployeeCategory’ class.

EmployeeCategory employeeCategory = new EmployeeCategory();

Then we have assigned values to FirstName, LastName and Category properties. Note that both FirstName and LastName properties are inherited from ‘Employee’ base class.

Next, we have called ‘PrinEmployeeCategory()’ method to print employee’s information to console output.

Save the application (Ctrl + S) and run the application (F5).

We will get the following output.

Ouput:

Name; Chittaranjan Dhurat
Category: Senior Level

With this demonstration, we have seen how a class member of one project having protected access modifier can be accessible to inherited class members of any other project.

Summary:

Access modifier Description
protected A class member can be accessed only by inherited class members within the same project and other projects.

In this section, we have seen how to use ’protected’ access modifier in the application. Hope you now know the accessibility level of a class member having ’protected’ access modifier.

C# Object Oriented Programming