Accessing a Private Constructor from Outside the Class in C#

New answer (nine years later)

There is now several overloads for Activator.CreateInstance that allow you to use non public constructors:

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

true = use non public constructors.

.

Old answer

Default constructors are private for a reason. The developer doesn't make it private for fun.

But if you still want to use the default constructor you get it by using reflection.

var constructor = typeof(Bob).GetConstructor(BindingFlags.NonPublic|BindingFlags.Instance, null, new Type[0], null);
var instance = (Bob)constructor.Invoke(null);

Edit

I saw your comment about testing. Never test protected or private methods / properties. You have probably done something wrong if you can't manage to test those methods/properties through the public API. Either remove them or refactor the class.

Edit 2

Forgot a binding flag.


There are several ways around this issue:

One: Make the constructor public. If you need to access it from outside the class why is it private (it might be that you only want to access the private constructor for testing, in which case this is a valid issue).

Two: Make the constructor protected, then access it through a derived class:

public class Bob
{
    public String Surname { get; set; }

    protected Bob()
    { }

    public Bob(string surname)
    {
        Surname = surname;
    }
}

public class Fred : Bob
{
    public Fred()
        : base()
    {
    }
}

Three: Use reflection (as shown by jgauffin).


In additional to @jgauffin's answer which tells how to call private constructors via reflection:

Is it possible to change the modifiers of the private constructor?

It seems that you are implementing Factory Pattern in your code. Thus the modifier is supposed to be internal.

public class Product
{
   //others can't create instances directly outside the assembly
   internal Product() { }    
}
public class ProductProvider
{
   //they can only get standardized products by the provider
   //while you have full control to Product class inside ProductProvider
   public static Product CreateProduct()
   {
       Product p = new Product();    
       //standardize the product
       return p;
   }  
}

Extension methods

public static MyExt
{
   public static void DoSomething(this Product p) { }
}

Calling p.DoSomething() actually equals to MyExt.DoSomething(p). It's not putting this method into class Product.