Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

inheritance

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

like image 994
The Cog Avatar asked Dec 03 '22 17:12

The Cog


1 Answers

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.

like image 152
BradleyDotNET Avatar answered Feb 20 '23 01:02

BradleyDotNET