Search code examples
c#oopinheritanceprotected

How to make protected members not accessible in a "grandchildren" class


I have the protected variable var1 in the abstract class AbstractModule

I create abstract class AbstractActivity : AbstractModule and use var1 from the parent class AbstractModule

Now I create class MyActivity : AbstractActivity and I want to make var1 not accessible in the MyActivity class.

How can I do it?

(I can create the protected property, but then I have the same problem)


Solution

  • C# does not allow this. But you can shadow the field in your class AbstractActivity by creating one with the same name. Your class MyActivity would then have access to the shadowed field and its value, but not to the field defined in AbstractModule.

      public class A
      {
         protected bool seeMe;
      }
    
      public class B : A
      {
         public B()
         {
            base.seeMe = false; // this is A.seeMe
         }
    
         protected bool seeMe;
      }
    
      public class C : B
      {
         public C()
         {
            seeMe = true; // this is B.seeMe
         }
      }
    

    The above example doesn't prevent code from being written that uses the shadow field. This may cause confusion if the programmer is aware of A.seeMe and thinks it is being set. You can force a compile error when B.seeMe is used by decorating it with the Obsolete attribute:

      public class B : A
      {
         public B()
         {
            base.seeMe = false; // this is A.seeMe
         }
    
         [Obsolete("cannot use seeMe", error:true)]
         protected bool seeMe;
      }
    
      public class C : B
      {
         public C()
         {
            seeMe = true; // this will give a compile error
         }
      }