5

Basically what I want to do is

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 the users of the Parent class can see the Nested class, but are unable to create it (they can however get it from Parent). I know that for normal methods you can do it with explicit interface implementation, but it doesn't seem to work with constructors.

sqd
  • 1,485
  • 13
  • 23

1 Answers1

3

You can simply return an INested, which allows you to mark the nested class as private; thus the class is only accessible by Parent. You end up with 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;
    }
}
Rob
  • 26,989
  • 16
  • 82
  • 98