Search code examples
c#derived-classnested-classpartial-classes

How can I derive a class nested inside a partial class?


If I have an abstract class nested inside a partial container class nested inside another class, how can I derive classes from the base class? I would think the following would work, but it says BaseClass isn't accessible due to protection level. I need the derived classes to be private though.

And before anyone tells me what a bad structure this is, this is why I might need it.

    class SingletonClass
    {
        public static partial class ContainerClass
        {
            abstract class BaseClass
            {

            }
        }
    }

    static partial class ContainerClass
    {
        class DerivedClass : BaseClass
        {

        }
    }

Solution

  • You code does not compile because there are two different ContainerClass types. One is a "normal" class and the other is nested in SingletonClass. If there are no namespace involved then the full name of the first is SingletonClass.ContainerClass while the full name of the second is ContainerClass (i.e., two different types).

    To do what you want you need to make SingletonClass partial also:

    partial class SingletonClass
    {
        public static partial class ContainerClass
        {
            abstract class BaseClass
            {
    
            }
        }
    }
    
    partial class SingletonClass
    {
        public static partial class ContainerClass
        {
            class DerivedClass : BaseClass
            {
    
            }
        }
    }