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 );
    }                    
}

Comments
gravatar Joshua Flanagan Friday, June 25, 2010
This caught me when I tried (and failed) to use a class with an optional parameter constructor to close a generic type that had a default constructor constraint -- new().

Makes perfect sense when you realize it is just compiler sugar.
gravatar Diego Mijelshon Saturday, June 26, 2010
It's not hard to implement an Activator wrapper that uses default parameters: http://gist.github.com/454424
gravatar scott Sunday, June 27, 2010
@Diego: Cool!
gravatar Diego Mijelshon Sunday, June 27, 2010
@scott, of course, you are more than welcome to post about the solution. I'm too lazy to blog :-)
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!