If a record declaration creates a cyclical reference, the compiler generated ToString() causes a stack overflow.When a record declaration has a property referencing itself, a reference cycle is generated which causes the compiler to write a ToString() method will cause a stack overflow. The C# language designers say this is by design and refuse to issue a compiler warning, while most merely mortals would consider this a bug. Even worse, the debugging session might stop abruptly and the developer has no way to figure out the problem, because the stack trace is no longer available. Be warned when you design your own records.
The new record feature of C# is supposed to make the life of developers easy. Just define the properties of a record and the compiler will autogenerate a class with some useful methods like ToString()
. However, if the developer is not careful, his design might cause the compiler to write code that will fail. This article gives a quick introduction into C# 9 records, explains the problem, what you have to do to rectify it and makes some suggestions how the C# compiler should be improved.