Search code examples
c#oopabstract-classinner-classesclass-visibility

Avoid Access to Constructor of nested Class


here a rougth code example to my problem:

class FooMaster
{
    private static FooChildBase GetFooChild(int number)
    {
        switch(number)
        {
            case 1:
                return new FooChild1();
            case 2:
                return new FooChild2();
            default:
                throw new NotImplementedException("...");    
        }
    }

    public static string GetFooChildText1Value(int number)
    {
        FooChildBase fooChild = GetFooChild(number);

        return (fooChild?.Text1) ?? throw new NullReferenceException("...");
    }

    ...

    class FooChild1 : FooChildBase
    {
        internal override string Text1 { get; } = "Test"

        public static void Test()
        {
            //Do something
        }
    }

    class FooChild2 : FooChildBase
    {
        internal override string Text1 { get; } = "Test"
    }
 
    abstract class FooChildBase
    {
        internal abstract string Text1 { get; }
    }
}

What i want to accomplish:

You should:

  • only be able to get to Text1 if you call 'GetFooChildText1Value' from another class then FooMaster
  • be able to access the values and constructors of FooChild1 and FooChild2 in FooMaster
  • not be able to call the constructor of FooChild1 or FooChild2 from outside FooMaster
  • --> also not be able to see the properties of FooChild1 or FooChild2 from outside FooMaster

EDIT:

The Types FooChild1 and FooChild2 must be known from outside because you need to be able to call individual public static methods directly (I don't want to make methods that only call the next method)


Solution

  • Update:

    In the End I created another class-library and defined the constructor as internal. That way it's only accessable in this assembly.

    The proposed interface solution could also have worked, but I would have had to create a separate interface for each class.

    Thanks for all the quick answers!