0

Why following code throws StackoverflowException?

class Foo { Foo foo = new Foo(); } class Program { static void Main(string[] args) { new Foo(); } } 
5
  • 12
    because each instance of Foo creates and instance of Foo which creates an instance of Foo.... Commented Oct 30, 2015 at 12:55
  • Foo creates an instance of itself during initialization. That's infinite recursion. Commented Oct 30, 2015 at 12:57
  • Every new object is created on a stack. In your case you create infinite amount of objects and your application runs out of memory. Commented Oct 30, 2015 at 13:00
  • [needed] What is a StackOverflowException and how do I fix it? :) Commented Oct 30, 2015 at 13:03
  • 'StackOverflowException' is thrown when is infinite recursion is started, or big/deep enough to exceed stack size. Commented Oct 30, 2015 at 13:19

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

5

Well, let´s see:

  1. Program runs main which executes new Foo();;
  2. new Foo() creates new Foo instance, including Foo foo field
  3. Foo foo = new Foo();executes new Foo (go to step 2)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.