#287 – You Don’t Have to Define a Constructor

It’s not mandatory for a user-defined class to define a constructor.  If one is not defined, the compiler will automatically generate a constructor. This internal constructor will just call the constructor of the class’ base class.  (E.g. The constructor in System.Object).

You can use the IL DASM tool to inspect the code for your class and see this automatically generated constructor.

For example, let’s say that we have a Dog class that does not define a constructor.  Below is an image of the IL DASM, showing the metadata for the Dog class.  Note that it shows the following elements in the class:

  • Age and Name properties
  • get and set accessors for the properties
  • Backing variables for the properties
  • A Bark method
  • A method called .ctor–this is the automatically-generated constructor

This constructor just calls the System.Object constructor:

Advertisements