These are accessibility keywords. Protected controls how other types (like derived types) in a C# program can access a class
and its members.
The protected modifier is between the private and public domains. It is the same as private but allows derived classes to access the member.
Consider 2 classes, A and B. Class
B is derived from A. If we look inside class
A, we see it has 2 int
fields: 1 protected and 1 private.
class
B, we can access the protected int
, but not the private int
. So protected gives us additional access in a derived class
.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(); } }0
The internal modifier, like others such as public and private, changes restrictions on where else the type can be accessed.
class
(just for this example). Any member type can also be modified with internal.class Program { static void Main() { // Can access the internal type in this program. Test test = new Test(); test._a = 1; } } // Example of internal type. internal class Test { public int _a; }
Consider the C# specification. It states that "The intuitive meaning of internal is: access limited to this program."
The internal keyword is mainly for information hiding. This improves program quality by forcing programs to be modular.
The "protected internal" modifier is a special case in the C# language. It is not precisely the same as both protected and internal.
The protected modifier, along with internal, restrict access to members in specific ways. Internal restricts a member to the current program.
And protected, meanwhile, is used with class
derivation. Protected makes it easier to keep a good level of information hiding while still allowing a rich object hierarchy.