Search code examples
c#stack-overflow

Why it is a StackOverFlow Exception?


Why following code throws StackoverflowException?

class Foo
{
    Foo foo = new Foo();
}
class Program
{
    static void Main(string[] args)
    {
        new Foo();
    }
}

Solution

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