C# Protected

  • The protected keyword is one of the access modifiers in C#.
  • A protected member of a class can only be accessed in the class and its derived classes.
  • The protected keyword is something like between public and private and provides a way to make some class members can only be accessed in the class inheritance hierarchy.

Example 01-54-01

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using System;

namespace TestProtected
{
    public class A
    {
        private int i = 1;
        protected int j = 2;
        public int k = 3;

        protected void outI()
        {
            Console.Write("i={0}, ", this.i);
        }
    }

    public class B : A
    {
        public void output()
        {
            //Console.Write("i={0}, ", this.i);
            outI();
            Console.WriteLine("j={0}, k={1}", this.j, this.k);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            B b = new B();
            b.output();
            //Console.WriteLine("j={0}, k={1}", b.j, b.k);
            Console.Read();
        }
    }
}

Output

i=1, j=2, k=3
  • Line 5-15: Define a public class A.
  • Line 7-9: Declare 3 fields of the class - a private field, a protected field and a public field.
  • Line 11-14: Define a protected method outI() to output the value of the private field i.
  • Line 17-25: Define a derived class B inheriting from A.
  • Line 19-24: Define a public method output() to print i, j and k.
  • Line 22: outI() method inherited from the protected method in A. The protected keyword allows the derived class to access the method in base class A.
  • Line 27-36: Program class is defined to test class A and B.
  • Line 29-35: Start Main method.
  • Line 31: Create an object of class B.
  • Line 32: Call the output() method of the object b to output the i, j and k.
  • Line 21: If the double slash // is removed, you will get a compile time error. Because i is a private integer field in class A and cannot be inherited from A in B.
  • Line 33: If the comment symbol // is removed, you will get a compile time error. Because the access modifier j is protected and can only be accessed in A or B. It can not be accessed in the Main method in Program class.

The last access modifier is protected internal which means the class member can be accessed in the class, derived class or the same assembly.