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");
}
}
CodePudding user response:
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
CodePudding user response:
Because when you do this:
new ArrayTest1()
You are creating an instance of ArrayTest1
. Which does this:
ArrayTest2 arrayTest2 = new ArrayTest2();
This creates an instance of ArrayTest2
. Which does this:
ArrayTest1 arrayTest1 = new ArrayTest1();
This creates an instance of ArrayTest1
. Which does this:
ArrayTest2 arrayTest2 = new ArrayTest2();
This creates an instance of ArrayTest2
. Which does this:
ArrayTest1 arrayTest1 = new ArrayTest1();
This creates an instance of ArrayTest1
...
And so on, indefinitely.
It's not clear what your goal is with the code. But what is clear is that your objects can't mutually depend on one another this way because the simple act of creating an instance of the object results in an infinite recursion.
Given only the code shown, the solution is to simply remove those mutually-dependent fields from the classes, since nothing ever uses them anyway:
public class ArrayTest1
{
public ArrayTest1()
{
Console.WriteLine($"{nameof(ArrayTest1)} Class Contructor Executed");
}
}
public class ArrayTest2
{
public ArrayTest2()
{
Console.WriteLine($"{nameof(ArrayTest2)} Class Contructor Executed");
}
}