title: Only allow Factory method to instantiate objects (prevent instantiation of base class AND uninitialized objects)
body: <p>I have a base class for handling &quot;jobs&quot;. A factory method creates derived &quot;job handler&quot; objects according to job type and ensures the job handler objects are initialized with all the job information.</p>
  <p><strong>Calling factory method to request a handler for Job and Person assigned:</strong></p>
  <pre><code>public enum Job { Clean, Cook, CookChicken }; // List of jobs.
  
    static void Main(string[] args)
    {
      HandlerBase handler;
      handler = HandlerBase.CreateJobHandler(Job.Cook, &quot;Bob&quot;);
      handler.DoJob();
      handler = HandlerBase.CreateJobHandler(Job.Clean, &quot;Alice&quot;);
      handler.DoJob();
      handler = HandlerBase.CreateJobHandler(Job.CookChicken, &quot;Sue&quot;);
      handler.DoJob();
    }
  </code></pre>
  <p><strong>The Result:</strong></p>
  <pre><code>Bob is cooking.
  Alice is cleaning.
  Sue is cooking.
  Sue is cooking chicken.
  </code></pre>
  <p><strong>Job handler classes:</strong></p>
  <pre><code>public class CleanHandler : HandlerBase
  {
    protected CleanHandler(HandlerBase handler) : base(handler) { }
    public override void DoJob()
    {
      Console.WriteLine(&quot;{0} is cleaning.&quot;, Person);
    }
  }
  
  public class CookHandler : HandlerBase
  {
    protected CookHandler(HandlerBase handler) : base(handler) { }
    public override void DoJob()
    {
      Console.WriteLine(&quot;{0} is cooking.&quot;, Person);
    }
  }
  </code></pre>
  <p><strong>A sub-classed Job Handler:</strong></p>
  <pre><code>public class CookChickenHandler : CookHandler
  {
    protected CookChickenHandler(HandlerBase handler) : base(handler) { }
    public override void DoJob()
    {
      base.DoJob();
      Console.WriteLine(&quot;{0} is cooking chicken.&quot;, Person);
    }
  }
  </code></pre>
  <p><strong>The best way of doing things? I have struggled with these issues:</strong></p>
  <ol>
  <li>Ensure that all derived objects have a fully initialized base object (Person assigned).</li>
  <li>Prevent instantiation of ANY objects other than through my factory method that performs all the initialization.</li>
  <li>Prevent instantiation of the base class object.</li>
  </ol>
  <h1>The Job handler <code>HandlerBase</code> base class:</h1>
  <ol>
  <li>A <code>Dictionary&lt;Job,Type&gt;</code> maps Jobs to Handler classes.</li>
  <li>PRIVATE setter for job data (i.e., Person) prevents access except by factory method.</li>
  <li>NO default constructor and PRIVATE constructor prevents construction except by factory method.</li>
  <li>A protected &quot;copy constructor&quot; is the only non-private constructor. One must have an instantiated HandlerBase to create a new object, and only the base class factory can create a base HandlerBase object. The &quot;copy constructor&quot; throws an exception if one attempts to create new objects from a non-base object (again, preventing construction except by the factory method).</li>
  </ol>
  <p>A look at the base class:</p>
  <pre><code>public class HandlerBase
  {
    // Dictionary maps Job to proper HandlerBase type.
    private static Dictionary&lt;Job, Type&gt; registeredHandlers =
      new Dictionary&lt;Job, Type&gt;() {
        { Job.Clean, typeof(CleanHandler) },
        { Job.Cook, typeof(CookHandler) },
        { Job.CookChicken, typeof(CookChickenHandler) }
      };
  
    // Person assigned to job. PRIVATE setter only accessible to factory method.
    public string Person { get; private set; }
  
    // PRIVATE constructor for data initialization only accessible to factory method.
    private HandlerBase(string name) { this.Person = name; }
  
    // Non-private &quot;copy constructor&quot; REQUIRES an initialized base object.
    // Only the factory method can make a HandlerBase object.
    protected HandlerBase(HandlerBase handler)
    {
      // Prevent creating new objects from non-base objects.
      if (handler.GetType() != typeof(HandlerBase))
        throw new ArgumentException(&quot;THAT'S ILLEGAL, PAL!&quot;);
  
      this.Person = handler.Person; // peform &quot;copy&quot;
    }
  
    // FACTORY METHOD.
    public static HandlerBase CreateJobHandler(Job job, string name)
    {
      // Look up job handler in dictionary.
      Type handlerType = registeredHandlers[job];
  
      // Create &quot;seed&quot; base object to enable calling derived constructor.
      HandlerBase seed = new HandlerBase(name);
  
      object[] args = new object[] { seed };
      BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
  
      HandlerBase newInstance = (HandlerBase)Activator
        .CreateInstance(handlerType, flags, null, args, null);
  
      return newInstance;
    }
  
    public virtual void DoJob() { throw new NotImplementedException(); }
  }
  </code></pre>
  <p><strong>A look at the Factory Method:</strong></p>
  <p>Because I have made public construction of a new object impossible without already having an instantiated base object, the factory method first constructs a <code>HandlerBase</code> instance as a &quot;seed&quot; for calling the needed derived class &quot;copy constructor&quot;.</p>
  <p>The factory method uses <code>Activator.CreateInstance()</code> to instantiate new objects. Activator.CreateInstance() looks for a constructor that matches the requested signature:</p>
  <p>The desired constructor is <code>DerivedHandler(HandlerBase handler)</code>, thus,</p>
  <ol>
  <li>My &quot;seed&quot; <code>HandlerBase</code> object is placed in <code>object[] args</code>.</li>
  <li>I combine <code>BindingFlags.Instance</code> and <code>BindingFlags.NonPublic</code> so that CreateInstance() searches for a non-public constructor (add <code>BindingFlags.Public</code> to find a public constructor).</li>
  <li>Activator.CreateInstance() instantiates the new object which is returned.</li>
  </ol>
  <h1>What I don't like...</h1>
  <p>Constructors are not enforced when implementing an interface or class. The constructor code in the derived classes is mandatory:</p>
  <pre><code>protected DerivedJobHandler(HandlerBase handler) : base(handler) { }
  </code></pre>
  <p>Yet, if the constructor is left out you don't get a friendly compiler error telling you the exact method signature needed: &quot;'DerivedJobHandler' does not contain a constructor that takes 0 arguments&quot;.</p>
  <p>It is also possible to write a constructor that eliminates any compiler error, instead--WORSE!--resulting in a run-time error:</p>
  <pre><code>protected DerivedJobHandler() : base(null) { }
  </code></pre>
  <p>I do not like that there is no means of enforcing a required constructor in derived class implementations.</p>