Home > database >  access protected members of another instance in derived class
access protected members of another instance in derived class

Time:07-19

Even though Iam in a derived class which should get me access to the derived protected members, I get the error

"Cannot access protected method 'BaseMethod' from here"

when trying to call other.BaseMethod();. Can I get around this without having to make BaseMethod public? I also cannot make the method internal, since Base and Derived are in different assemblies.

class Base
{
  protected void BaseMethod() { }
}

class Derived: Base
{
  public void Doit(Base other)
  {
    other.BaseMethod();
  }
}

CodePudding user response:

You are using another class, as parameter, not the derived one.

in this case, the method should be public.

but have a look a this How do you unit test private methods?

CodePudding user response:

You can get around this by adding protected internal:

class Base
{
    protected internal void BaseMethod() { }
}

class Derived : Base
{
    public void Doit(Base other)
    {
        other.BaseMethod();
    }
}

However, when inheritance is used then it can be called without any params. Let me show an example:

class Base
{
    protected internal void BaseMethod() { }
}

class Derived : Base
{
    public void Doit()
    {
        BaseMethod();
    }
}
  • Related