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
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.
is the opposite to public
variables and methods can only be accessed from within the class.
But what does 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.
private String PrivateString = "This string is private";
protected String ProtectedString = "This string is protected";
class Child: Parent
public void Display()
// This won't work
static int Main(string args)
Child child = new Child();
// Wait for a keypress
This string is protected
[If you're looking for one-to-one online lessons in C#, contact me]