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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With