Search code examples
c#constructorvisibilitynested-class

Visibility of nested class constructor


Is there a way to limit the instantiation of the nested class in C#? I want to prevent nested class being instantiated from any other class except the nesting class, but to allow full access to the nested class from other code.


Solution

  • Usually I create an interface for the functionality you want to expose to other classes, then make the nested class private and implement that interface. This way the nested class definition can stay hidden:

    public class Outer
    {
        private class Nested : IFace
        {
            public Nested(...)
            {
            }
            //interface member implementations...
        }
    
        public IFace GetNested()
        {
            return new Nested();
        }
    }