Why can't I access a protected method from a subclass in C #?

Why can't I access a protected method from a subclass in C #?

Grade:

public abstract class A
{
    protected void Method()
    {

    }
}

Subclass:

public class B : A
{

}

Console Application:

B b = new B();

b.Method();

The compiler says: Error 1 "Method ()" is unavailable due to protection level

+4
source share
1 answer

protectedmeans that does not mean that client code can access it through an instance of a derived class.

It does mean that the code of the derived class can use it. For example, this would be true:

public class B : A
{
     public void SomeMethod()
     {
          Method();
     }
}

If you want your exact code sample to work, mark Methodhow public.

+17
source

All Articles