I worked with a developer that had many years my senior in C# experience. I no longer have a way to contact him and I remember him saying that it's not a good idea to include code in a default parameter less constructor but I cannot remember the reason why.
Is it good practice or bad practice to include code in the default constructor in C# or any language for that matter?
Calling instance method in constructor is dangerous as the object is not yet fully initialized (this applies mainly to methods than can be overridden). Also complex processing in constructor is known to have a negative impact on test-ability.
There can be multiple constructors in a class. However, the parameter list of the constructors should not be same. This is known as constructor overloading.
No, you cannot call a constructor from a method. The only place from which you can invoke constructors using “this()” or, “super()” is the first line of another constructor.
Yes, as mentioned we can call all the members of a class (methods, variables, and constructors) from instance methods or, constructors.
It depends on the situation, but it is definitely NOT bad practice to put code in default constructors. If you need to, go ahead and do it.
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