Optional Parameters Do Not Create Default Constructors

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

Print | posted @ Thursday, June 24, 2010 9:12 PM

Comments on this entry:

Gravatar # re: Optional Parameters Do Not Create Default Constructors
by Joshua Flanagan at 6/25/2010 8:23 AM

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 # re: Optional Parameters Do Not Create Default Constructors
by Diego Mijelshon at 6/26/2010 7:06 PM

It's not hard to implement an Activator wrapper that uses default parameters: http://gist.github.com/454424
  
Gravatar # re: Optional Parameters Do Not Create Default Constructors
by scott at 6/27/2010 10:01 AM

@Diego: Cool!
  
Gravatar # re: Optional Parameters Do Not Create Default Constructors
by Diego Mijelshon at 6/27/2010 6:59 PM

@scott, of course, you are more than welcome to post about the solution. I'm too lazy to blog :-)
  
Comments have been closed on this topic.
Scott Allen
Posts - 869
Comments - 4493
Stories - 14