Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protected method access from derived class

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?

like image 400
user3165438 Avatar asked Mar 24 '14 09:03

user3165438


1 Answers

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.

like image 198
Suresh Kumar Veluswamy Avatar answered Oct 08 '22 02:10

Suresh Kumar Veluswamy