OdeToCode IC Logo

Optional Parameters Do Not Create Default Constructors

Thursday, June 24, 2010

At least not from the reflection API's point of view.

For example, given the following class ...

public class Wig
{
    public Wig(string name = "Angry")
    {
        // ...
    }
}

... you can successfully instantiate the class as if it had a default, parameterless constructor:

var wig = new Wig();

However, trying to do this via Activator will fail:

var wig = Activator.CreateInstance<Wig>();
// MissingMethodException: 
// No parameterless constructor defined for this object.

Which makes sense once you realize optional parameters are compiler sugar, and the following code will clearly show a single constructor requiring a single argument.

var ctors = typeof(Wig).GetConstructors();
foreach (var ctor in ctors)
{
    Console.WriteLine(ctor.Name);
    foreach(var param in ctor.GetParameters())
    {
        Console.WriteLine("\t{0} {1}", 
            param.Name, 
            param.ParameterType.Name );
    }                    
}