C # How to expose the constructor of a nested class only to members of the parent class?

I mainly want to do

class Parent{    
    public class Nested {
        private Nested(){
            //do something
        }
        /* ??? */ Nested CreateNested(){
            return new Nested ();   
        }
    }

    public Nested Foo(){
        Nested n = (???).CreateNested ();
        // do something about n
        return n;
    }
}

so that users of the class Parentcan see the class Nestedbut cannot create it (they can, however, get it from Parent). I know that for ordinary methods you can do this with an explicit implementation of the interface, but it does not work with constructors.

+4
source share
1 answer

You can simply return INestedwhich allows you to mark the nested class as private; thus, the class is available only Parent. You will get something like this:

public class Parent
{
    public interface INested
    {
    }
    private class Nested : INested
    {
        public Nested()
        {
        }
    }

    public INested Foo()
    {
        Nested n = new Nested();
        // do something about n
        return n;
    }
}
+3
source

Source: https://habr.com/ru/post/1674721/


All Articles