A practical definition of C# constructors

What’s the textbook definition of a constructor in C#? According to Microsoft (emphasis added):

Whenever a class or struct is created, its constructor is called. A class or struct may have multiple constructors that take different arguments. Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible and easy to read.

That’s not a great definition, but it tells us some important things:

  • There can be many constructors.
  • Constructors may or may not have parameters.
  • Constructors should be used to:
    • set default values,
    • perform limited initialization, and
    • be simple.

In other words, constructors should do as little as possible.

Constructors should:

  • initialize fields and properties
  • check the runtime configuration and environment
  • fail if the object can not be set up properly
  • be consistent, in therms of logic (when using multiple constructors)
  • be thread-safe

Constructors should not:

  • invoke complex business logic (example)
  • use out parameters (example)
  • accept arrays, except as params (use collection types instead)

I’m sure there is more, but those are my guidelines.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.