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 :
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