I have a protected method in base class :
public class BaseClass
{
protected virtual void Foo(){}
}
The method is overrided one of the derived classes:
public class Derived1 : BaseClass
{
protected override void Foo()
{
//some code...
}
}
Another derived class has an instance of the first derived class.
When I try to access the Foo method (existing in base class, as mentiond) I get an error :
public class DerivedClass2 : BaseClass
{
BaseClass instance = new DerivedClass1();
instance.Foo(); // Here I get an error
}
The error I get:
Error CS1540: Cannot access protected member 'BaseClass.Foo' via a qualifier of type 'BaseClass';
the qualifier must be of type 'DerivedClass2' (or derived from it)
I understand that protected members should not give up their value to any other instance, even an instance derived from the same type,
but is there a way not to modify the method as public?
You can make the Foo method declaration as protected internal....
public class BaseClass
{
protected internal virtual void Foo(){}
}
public class Derived1 : BaseClass
{
protected internal override void Foo()
{
//some code...
}
}
Here "protected internal" means the member is visible to any class inheriting the base class, whether it's in the same assembly or not. The member is also visible via an object declared of that type anywhere in the same assembly.
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