简体   繁体   中英

Process is terminating due to StackOverflowException on calling GetType()

I came across this by accident when forgetting a static modifier and have simplified it to a reproducible snippet. The following will fail with a StackOverflowException when ran:

namespace test
{
    class Program
    {
        Program program = new Program();

        public static void Main(string[] args)
        { 
            var p = new Program();
            System.Console.WriteLine(p.GetType());
        }
    }
}

Why does this fail? Is it a bug or my misunderstanding of the CLR?

The offending line isn't p.GetType() , but the type initializer of Program .

When you create the program instance var p = new Program(); it runs the initializer of Program to set up the new instance. That includes running any assignments to the fields of Program .

This initialized field is the culprit:

Program program = new Program();

To create an instance of Program , you must initialize the field program by creating a new instance of Program . This causes an infinite stack of initializers and generates your StackOverflowException .

I think that it will recursively try to create new Program() objects until the stack overflows because of the lines:

class Program
{
    Program program = new Program();

You create a program, which then creates a program, which then creates a program ... etc to infinity.

I am unsure what you need to accomplish here but if you need to make an instance of a class within the same class I would assume you need to hit a base case eventually in order to stop the recursion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM