C# Protected

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

Example

Private keyword

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.

Int

Note:The accessibility domain of protected fields includes all derived classes. This is a key difference.

C# program that uses protected modifier

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).

Internal

Derived classes in other programs will still be able to use the member. The modifier does not prevent this. It is less restrictive than just protected. And it is not as common in programs.

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.

Review:Protected makes it easier to keep a good level of information hiding while still allowing a rich object hierarchy.


C#: Class