How to instantiate an object with a private constructor in C#?

You can use one of the overloads of Activator.CreateInstance to do this: Activator.CreateInstance(Type type, bool nonPublic)

Use true for the nonPublic argument. Because true matches a public or non-public default constructor; and false matches only a public default constructor.

For example:

    class Program
    {
        public static void Main(string[] args)
        {
            Type type=typeof(Foo);
            Foo f=(Foo)Activator.CreateInstance(type,true);
        }       
    }

    class Foo
    {
        private Foo()
        {
        }
    }

Leave a Comment