C# Protected Modifier

The C# programming language

Protected is an accessibility keyword. When should you use this modifier in your C# programs? The protected modifier is between the private and public domains. It is the same as private but allows derived classes to access the member.

Keywords

This C# article explains the protected keyword. It provides an example program.

Example

Note

This program introduces two classes, A and B. B is derived from A. Class A has two fields, a protected int and a private int. In class B, we can access the protected int, but not the private int. This is because the accessibility domain of protected fields includes all derived classes.

Program that uses protected modifier [C#]

using System;

class A
{
    protected int _a;
    private int _b;
}

class B : A
{
    public B()
    {
	// Can access protected int but not private int!
	Console.WriteLine(this._a);
    }
}

class Program
{
    static void Main()
    {
	B b = new B();
    }
}

Output

0

Protected internal

Programming tip

The "protected internal" modifier is a special case in the C# language. It means both internal accessibility (all parts of this program can use the member) and protected accessibility (all derived classes can use the member). Note that derived classes in other programs will still be able to use it.

Internal

Summary

The protected modifier provides a way to have a member be more visible than private but less than public. It facilitates the development of object-oriented programs that use class derivation. Protected makes it easier to keep a good level of information hiding while still allowing a rich object hierarchy.

Class Examples
.NET