Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why I'm getting StackOverflowException?

I’m getting StackOverflowException when I run below program. My doubt is how this program recursively calling each classes(ArrayTest1, ArrayTest2) fields without executing constructor method?

using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        var arraryTest = new ArrayTest1();
    }
}

public class ArrayTest1
{
    ArrayTest2 arrayTest2 = new ArrayTest2();
    public ArrayTest1()
    {
        Console.WriteLine($"{nameof(ArrayTest1)} Class Contructor Executed");
    }
}

public class ArrayTest2
{
    ArrayTest1 arrayTest1 = new ArrayTest1();
    public ArrayTest2()
    {
        Console.WriteLine($"{nameof(ArrayTest2)} Class Contructor Executed");
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Because you create an infinite chain of ArrayTest1 -> ArrayTest2 -> ArrayTest1 -> ArrayTest2 -> …

To understand why you are not getting any output, see C# constructor execution order

Important steps in your case (no inheritance involved):

  • Member variables are initialized to default values
  • Variable initializers are executed
  • The constructor bodies are executed

You never reach constructor bodies, as the stack overflow happens in variable initializer

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading