4

I was wondering if it was possible in c# to do:

public class Outer 
{
    public class Inner {}   

    public Inner CreateInner() 
    {   
        return new Inner(); // should only be allowed inside this method
    }
}

where you can only create a new instance of the Inner class inside an Outer class method. I want to do this because I need better control over what Inner class is created and it helps me mock the return value of CreateInner and verify that it was called. Is this possible?

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
Mayron
  • 2,146
  • 4
  • 25
  • 51

1 Answers1

4

Making the default constructor private does not work, as you have probably already discovered.

However, you could declare a public nested interface and return that instead, and make the concrete class entirely private.

Something like this:

public class Outer
{
    public interface IInner
    {
        string SomeMethod();
    }

    class Inner: IInner
    {
        public string SomeMethod()
        {
            return "Hello, World!";
        }
    }

    public IInner CreateInner()
    {
        return new Inner(); // should only be allowed inside this method
    }
}
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276