title: Allow access to but prevent instantiation of a nested class by external classes
body: <p>I'm looking to define a nested class that is accessible to the container class and external classes, but I want to control instantiation of the nested class, such that only instances of the container class can create new instances of the nested class.</p>
  
  <p>The proceeding code should hopefully demonstrate this:</p>
  
  <pre><code>public class Container
  {
      public class Nested
      {
          public Nested() { }
      }
  
      public Nested CreateNested()
      {
          return new Nested();  // Allow
      }
  }
  
  class External
  {
      static void Main(string[] args)
      {
          Container containerObj = new Container();
          Container.Nested nestedObj;
  
          nestedObj = new Container.Nested();       // Prevent
          nestedObj = containerObj.CreateNested();  // Allow
  
      }
  }
  </code></pre>
  
  <p><code>Nested</code> must be public in order for it to be accessible by <code>External</code>. I tried making the constructor for <code>Nested</code> protected, however that prevents <code>Container</code> from creating instances, as <code>Container</code> isn't a base class of <code>Nested</code>. I could set the constructor for <code>Nested</code> to <code>internal</code>, but I'm looking to prevent access to the constructor by all external classes, including those in the same assembly. Is there a way to do this?</p>
  
  <p>If this cannot be achieved through access modifiers, I wonder if I could throw an exception within <code>Nested()</code>. However, I don't know how to test for the context within which <code>new Nested()</code> is called.</p>