Search code examples
c#oopinheritanceencapsulation

C# internal types in protected fields


I am trying to write a class library as following:

namespace Test
{
    class Field
    { 
    }

    public abstract class SomeClass
    {
        protected Field field;  //Inconsistent accessibility: field type 'Field' is less accessible than field 'SomeClass.field'
    }

    public class SomeDerivedClass1:SomeClass
    {
    }

    public class SomeDerivedClass2:SomeClass
    {
    }
}

Rules:

  1. I do not want to make Field a protected subclass of SomeClass, because it is used by other classes;
  2. I do not want to make Field visible outside of Test namespace, because it's breaks encapsulation;
  3. I need inheritance, because SomeDerivedClass1 and SomeDerivedClass2 share a lot of code.

Is any workaround for this problem without breaking any of these rules?


Solution

  • You can use the new private protected modifier. This is the equivalent of internal AND protected.

    Not to be confused with protected internal which is protected OR internal

    public abstract class SomeClass
    {
        private protected Field field;
    }
    

    It is still visible in the same assembly outside the namespace though.