Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
Why following code throws StackoverflowException?
StackoverflowException
class Foo { Foo foo = new Foo(); } class Program { static void Main(string[] args) { new Foo(); } }
Foo
[needed]
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.
Main
This leads to infinite recursion and a StackOverflowException being thrown.
StackOverflowException
Add a comment
Well, let´s see:
main
new Foo();
new Foo()
Foo foo
Foo foo = new Foo();
new Foo
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.
Foocreates and instance ofFoowhich creates an instance ofFoo....[needed]What is a StackOverflowException and how do I fix it? :)