The protected keyword is a member access modifier. A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.
A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type. For example, consider the following code segment:
class A { protected int x = 123; } class B : A { void F() { A a = new A(); B b = new B(); a.x = 10; // Error b.x = 10; // OK } }
The statement a.x =10
generates an error because A is not derived from B.
Struct members cannot be protected because the struct cannot be inherited.
It is an error to reference a protected member from a class, which is not derived from the protected member's class.
For more information on protected members, see Protected Access in the Language Reference.
For a comparison of protected with the other access modifiers, see Accessibility Levels.
In this example, the class MyDerivedC
is derived from MyClass; therefore, you can access the protected members of the base class directly from the derived class.
using System; class MyClass { protected int x; protected int y; } class MyDerivedC: MyClass { public static void Main() { MyDerivedC mC = new MyDerivedC(); // Direct access to protected members: mC.x = 10; mC.y = 15; Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y); } }
x = 10, y = 15
If you change the access levels of x
and y
to private, the compiler will issue the error messages:
'MyClass.y' is inaccessible due to its protection level. 'MyClass.x' is inaccessible due to its protection level.
C# Keywords | Access Modifiers | Accessibility Levels | Modifiers