The C# parameterless default constructor
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:
Unless the class is static, classes without constructors are given a public default constructor by the C# compiler in order to enable class instantiation.
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.
This is a problem I often run into when creating a custom resolver for AutoMapper (implementing the IValueResolver
interface) for example.
Your only option is to recreate the parameterless constructor:
Updated in April 2018:
I have posted a new post about why the last line was actually a wrong assumption. You can read it here.
See something wrong or want to ask a question? Get in touch on Twitter