Private Protected Access Modifier in C#

As we know, protected types available in the base class as well as in child class, which inherits base class. Private types are available only within the type where it declared. Private Protected access modifier types available only within the declare scope as well as child class, which inherits it.

Private Protected access modifier is available in C# 7.2 and above only.

namespace PrivateProtectedExp
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }

    class Company
    {
        private protected int id = 100;
    }

    class Employee: Company 
    {
        Employee()
        {
            Company objComp = new Company();

            //it gives the error because private protected types available within the declare type only
            int empId = objComp.id;

            //it works here because private protected types available in the derived class
            int empId = id;
        }
    }
}

As shown above, we have declared the id as private protected in Company class. This id is not available in Employee class through Company object because private protected types available only within the declare type. But directly, we can access id value in the Employee class constructor because Employee class derived from the company class and private protected types available in derived classes.

Add comment