Why is "internal const" being overridden in a child class but "protected const" can't?
Sample code:
class A
{
internal const string iStr = "baseI";
protected const string pStr = "baseP";
void foo()
{
string s = B.iStr; //childI
string t = B.pStr; //baseP
}
}
class B : A
{
internal new const string iStr = "childI";
protected new const string pStr = "childP";
}
Expected B.pStr to return "childP".
CodePudding user response:
Protected members can only be accessed within the same class as they are declared, or in derived classes of the class in which they are declared.
Therefore, the protected pStr
declared in B
, with the value "childP", cannot be accessed in the parent class A
.
Note that you are not "overriding" anything, which usually involves the override
keyword. You are simply declaring two new members in B
, in addition to those that B
inherits from A
. In total, B
has the following constants:
internal const string iStr = "baseI";
protected const string pStr = "baseP";
internal new const string iStr = "childI";
protected new const string pStr = "childP";
Accessible members that are declared in B
are preferred over inherited members with the same name. In other words, the members declared in B
hides the ones declared in A
(and does so explicitly with new
). Therefore, when you do B.iStr
, you get "childI". When you do B.pStr
however, you can only access the inherited member.
CodePudding user response:
Since the new const B.pStr
is protected, it is visible in B
and classes derived from B
only. So, it is invisible in class A
.
Note that the new
keyword in this context hides inherited members. Constants are static and cannot be overridden.