C# – Why a while(true) Loop in a Constructor is Bad

Architecturec

Albeit a general question my scope is rather C# as I am aware that languages like C++ have different semantics regarding constructor execution, memory management, undefined behaviour, etc.

Somebody asked me an interesting question which was for me not easily answered.

Why (or is it at all?) regarded as bad design to let a constructor of a class start a never ending loop (i.e. game loop)?

There are some concepts that are broken by this:

  • like the principle of least astonishment, the user does not expect the constructor to behave like this.
  • Unit tests are harder as you cannot create this class or inject it as it never exits the loop.
  • The end of the loop (game end) is then conceptually the time where the constructor finishes, which is also odd.
  • Technically such a class has no public members except the constructor, which makes it harder to understand (especially for languages where no implementation is available)

And then there are technical issues:

  • The constructor actually never finishes, so what happens with GC here? Is this object already in Gen 0?
  • Deriving from such a class is impossible or at least very complicated due to the fact that the base constructor never returns

Is there something more obviously bad or devious with such an approach?

Best Answer

What is the purpose of a constructor? It returns a newly constructed object. What does an infinite loop do? It never returns. How can the constructor return a newly constructed object if it doesn't return at all? It can't.

Ergo, an infinite loop breaks the fundamental contract of a constructor: to construct something.