Protected Access Modifier in C# with Example

C#In inheritance in C#, we know that all the public type members in base class are accessible through derived class.  Private type members in base class cannot be accessed through derived class.  Apart from Public and Private access modifiers, there is another access modifier called Protected access modifier.  By using Protected access modifier, you can access a protected type member in base class through its derived class only.

There are 3 ways to access protected type member.

  1. Create instance of derived class and access the member.
  2. Use base keyword.
  3. Use this keyword.

Example is given below for all 3 solutions.

using System;



namespace Hello_World
{

    class Customer
    {
        protected string _name;      



        public void PrintName()
        {
            Console.WriteLine(_name);
        }

    }

   class Customer2 : Customer
    {
     
       //Creating Instance of Derived Class
       public void PrintMehodOne()
       {
           Customer2 cust = new Customer2();
           cust._name = "Method 1";
           cust.PrintName();
       }

       //Using this keyword
       public void PrintMehodTwo()
       {
           this._name = "Method 2";
           PrintName();
       }

       //Using base keyword
       public void PrintMehodThree()
       {
           base._name = "Method 3";
           PrintName();
       }
       
    }

    class Program
    {
        static void Main(string[] args)
        {
            Customer2 cust2 = new Customer2();
            cust2.PrintMehodOne();
            cust2.PrintMehodTwo();
            cust2.PrintMehodThree();
        }
    }
}
;

 Output:

Method 1
Method 2
Method 3
Press any key to continue . . .

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •