Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty constructor or no constructor

Tags:

c#

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 {         ...... } 
like image 727
Ram Avatar asked Jun 03 '10 06:06

Ram


People also ask

Is an empty constructor necessary?

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.

Can we have an empty constructor?

Empty constructor just gives you an instance of that object. You might use setters on it to set necessary properties.

What is called Empty constructor?

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.

Why do we need empty constructor in C#?

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.


1 Answers

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.

like image 194
Soe Moe Avatar answered Sep 17 '22 00:09

Soe Moe