Search code examples
c#constructordefault-constructor

What benefits do empty constructors provide in C#?


I came to the existing project in C#. I can see that several classes have empty parameter-less constructors. Either public ones, or internal ones. The classes themselves are also public or internal. I can see neither other constructors in there, nor inheritance. I wonder what benefit this can have.

I expected that if there is absolutely no constructor, then C# compiler always creates one parameter-less empty constructor. So my question is: Is the current code (in above mentioned conditions) anyhow different than if there were no constructors? I think the only special case is internal constructor in a public class. Am I missing something more?


Solution

  • well, "or internal ones" is a significant change; the default constructor would be public.

    However, usually the reasons I see this is so that if somebody adds a specific constructor later, it doesn't represent a breaking change. Constructors are unusual in that adding a custom constructor can suddenly break things because it might remove the default constructor; this has consequences - including things that don't show until runtime (deserialization, for example), or until a downstream consumer of a library complains that you've broken the API.

    Likewise, if the type is ever used in reflection (perhaps as a plugin): Activator.CreateInstance usage won't show errors due to a removed parameterless constructor until runtime.

    Whether you actually need to do this is largely a matter of opinion, of course.