#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:

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. Pingback: #291 – No Default Constructor if You Definy any Constructors « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: