I think it is not mandatory to have a default constructor in a class (C#).
So, in that situation shall I have an empty constructor in the class or can I skip it?
Is it a best practice to have an empty default constructor?
Class test { public test() { } ...... }
or
Class test { ...... }
An empty constructor is needed to create a new instance via reflection by your persistence framework. If you don't provide any additional constructors with arguments for the class, you don't need to provide an empty constructor because you get one per default.
Empty constructor just gives you an instance of that object. You might use setters on it to set necessary properties.
In computer programming languages, the term default constructor can refer to a constructor that is automatically generated by the compiler in the absence of any programmer-defined constructors (e.g. in Java), and is usually a nullary constructor.
If you declare an empty constructor, the C# compiler will not dynamically generate a parameter-less constructor. If you do not use an access modifier with the constructor, it will also become a private constructor by default. Using the private keywords makes it obvious for developers by explicitly stating the type.
If the class won't be used by third parties and you don't need an overloaded constructor, don't write an empty constructor.
But...
Imagine you already shipped the product, and third parties use your class. A few months later there's a new requirement that makes you add a constructor with an argument.
Now, by doing so, the C# compiler no longer generates a default constructor. If you don't add an empty constructor explicitly, the third party code will be break.
In my opinion, you should always define empty constructors (one liner) for public classes used by third parties.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With