Search code examples
c#visual-studio-2010encapsulationprotectedderived-class

C# accessing protected member in derived class


I wrote the following code:

public class A                             
{
    protected string Howdy = "Howdy!";     
}

public class B : A                           
{
    public void CallHowdy()
    {
        A a = new A();
        Console.WriteLine(a.Howdy);
    }
}

Now, in VS2010 it results in the following compilation error:

Cannot access protected member 'A.a' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it).

This seems quite illogical to me - why can't I access the protected field of the class instance from a method of the class, which is derived from it?

So, why does this happen?


Found a strict answer - https://web.archive.org/web/20101104024941/http://blogs.msdn.com/b/ericlippert/archive/2005/11/09/491031.aspx


Solution

  • You're not accessing it from inside the class, you're trying to access the variable as though it were public. You would not expect this to compile, and this is pretty much what you are trying to do:

    public class SomethingElse
    {
        public void CallHowdy()
        {
            A a = new A();
            Console.WriteLine(a.Howdy);
        }
    }
    

    There is no relationship, and it sounds like you are confused why that field is not public.

    Now, you could do this, if you wanted to:

    public class B : A
    {
        public void CallHowdy()
        {
            Console.Writeline(Howdy);
        }
    }
    

    Because B has inherited the data from A in this instance.