Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# const protected vs internal

Why "internal const" can be overridden in 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".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading