C# accessing protected member in derived class

Yippie-Ki-Yay picture Yippie-Ki-Yay · May 18, 2012 · Viewed 7.8k times · Source

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 - http://blogs.msdn.com/b/ericlippert/archive/2005/11/09/491031.aspx

Answer

Tejs picture Tejs · May 18, 2012

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.