There’s not many things in C# that I wish were different, but this is one of them.
If you define a
class, it comes with a default parameterless constructor if you don’t define one:
If a class contains no instance constructor declarations, a default instance constructor is automatically provided. That default constructor simply invokes the parameterless constructor of the direct base class.
So this class:
is equivalent to this one:
So far so good. Now if you have a constructor with a parameter taking a default value, this rule doesn’t apply anymore.
In the following example, the parameterless contructor is not automatically provided:
In most cases, you would be creating an instance using
new as in
var foo = new Foo() and shouldn’t care much about the missing default constructor.
But if you are using reflection as in
var o = Activator.CreateInstance(typeof(Foo));, you will be out of luck. Doing so will give you a
System.MissingMethodException, No parameterless constructor defined for this object.
Your only option is to recreate the parameterless constructor:
The reasoning behind this is probably that the default parameterless constructor calls the base class one and for consistency it shouldn’t call anything else (because this is how it was defined). Still would be a nice to have…
See something wrong or want to ask a question? Get in touch on Twitter