Search code examples
c#classoopaccess-modifiers

access protected members of another instance in derived class


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();
  }
}

Solution

  • 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();
        }
    }