The Cog
The Cog

Reputation: 173

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#?

Class:

public abstract class A
{
    protected void Method()
    {

    }
}

Subclass:

public class B : A
{

}

Console application:

B b = new B();

b.Method();

Compiler says: Error 1 'Method()' is inaccessible due to its protection level

Upvotes: 4

Views: 2450

Answers (1)

BradleyDotNET
BradleyDotNET

Reputation: 61339

protected does not mean that client code can access it through a derived class instance.

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

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

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

Upvotes: 17

Related Questions