Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between default constructor and paramterless constructor?

Tags:

c#

A default constructor has no parameters. And nor does a constructor that you write with no parameters. So what is the ultimate difference in c#?

Added to this when you inherit a default constructor and a parameterless constructor are they exposed on the inheritting type exactly the same? Because my IOC container doesn't seem to think so. (Unity).

Cheers, Pete

like image 454
Exitos Avatar asked Jul 20 '26 18:07

Exitos


2 Answers

The "default" constructor is added by the C# compiler if your class does not contain an explicit instance constructor. It is a public, parameterless constructor. If you have created an explicit non-public, parameterless constructor, Unity will not be able to use it in the same way it would have used a public constructor (regardless of whether this was generated by the compiler, and regardless of whether it had parameters).

like image 84
Nicole Calinoiu Avatar answered Jul 23 '26 08:07

Nicole Calinoiu


You can override the behaviour of the default constructor by creating a parameterless constructor. A common use of this is when you have a custom object as a member of your class and you need to initialize it with a default value when an instance of your class created.

like image 25
superM Avatar answered Jul 23 '26 06:07

superM