My way or the highway! Activator.CreateInstance

I have an object that I always need created in one specific way. Its bits have to be loaded in a certain order and I want to control whenever that happens. Any other code requiring this object has to call my loader method.

I implement like this, using Activator.CreateInstance:

  1. Give the object a private constructor.
public class Monkey
{
     private Monkey()
     {}
}

2. In my loader class, I use Activator.CreateInstance like this:

(Monkey)Activator.CreateInstance(typeof(Monkey), true);

I also use this same activator code to spin up one of these monkeys in my test classes.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.