C# Protected: Using the Protected Keyword in C#

In C#, you can specify that instance variables and methods are public, protected, internal or private.

If the internal keyword is unfamiliar to you, you might want to check out my article on methods in C#.






Chances are you already know what public and private mean. public means that your object's method can be called from anywhere, or that the instance variable that you declare public can be accessed from anywhere, whether outside or inside the class itself.

private is the opposite to public: private variables and methods can only be accessed from within the class.

But what does protected do?

protected is useful when you want your class and all derived (child) classes to be able to access the method or variable, but you don't want it to be public.

Below is a complete program in C#. We create a Parent class containing a private and a protected variable. We derive a Child class from the Parent class. Then in the main program we create an object of type Child and call its Display() method.

Note that the Display() method cannot access the private variable, but it can access the protected variable. The protected variable is still not public however -- it is protected from being accessed outside of the Parent class and its subclasses.





using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Parent
    {
        private String PrivateString = "This string is private";
        protected String ProtectedString = "This string is protected";
    }

    class Child: Parent
    {
        public void Display()
        {
            Console.WriteLine(ProtectedString);

            // This won't work
            //Console.WriteLine(PrivateString);
        }
    }

    class Program
    {
        static int Main(string[] args)
        {
            Child child = new Child();
            child.Display();

            // Wait for a keypress
            Console.ReadKey();

            return 0;
        }
    }
}




This string is protected




[If you're looking for one-to-one online lessons in C#, contact me]