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.
- 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.