Why following code throws StackoverflowException
?
class Foo
{
Foo foo = new Foo();
}
class Program
{
static void Main(string[] args)
{
new Foo();
}
}
In Main
you create a new Foo
object, invoking its constructor.
Inside the Foo
constructor, you create a different Foo
instance, again invoking the Foo
constructor.
This leads to infinite recursion and a StackOverflowException
being thrown.