简体   繁体   中英

Following code throws Process is terminating due to StackOverflowException in the output. Why?

I am new to C#, following is my code, when I run it, it throws Process is terminating due to StackOverflowException in the output.Why??

namespace LearningCSharp
{
    class Program
    {
        //I have created the below object, I have not use it in main() method 
        //  but still because this ouput says StackOverflowException
        Program ProgramObject = new Program();//removing "= new Program() " ,then it works fine

    static void Main(string[] args)
    {
        Program po = new Program();
        po.testing();
    }
    void testing()
    {
        Console.WriteLine("Testing is Ok");
    }
  }
}

The main issue is creating an instance of Program inside itself:

namespace LearningCSharp
{
    class Program
    {
        Program ProgramObject = new Program(); // The runtime will try to create an instance of this when the class is created (instantiated)... but since the class is creating an instance of itself, that instance will also try to create an instance and so on... this goes on forever until there isn't enough memory on the stack to allocate any more objects - a stack overflow.

        ... other code here
    }
}

A console application requires a static method that is called when the app starts:

static void Main(string[] args)

This static method cannot see instance members - so you will either need to make your testing() method static:

    static void Main(string[] args)
    {
        testing();
    }

    static void testing()
    {
        Console.WriteLine("Testing is Ok");
    }

or create another class that you can instantiate

namespace LearningCSharp
{
    class Program
    {

        static void Main(string[] args)
        {
            TestClass test = new TestClass();
            test.testing();
        }
    }
}

class TestClass 
{
    internal void testing()
    {
        Console.WriteLine("Testing is Ok");
    }
}

Note that the accessor for the testing() method should be internal or public or the Main class will not have access to it.

You can create it like this:

class Program
{

    static Program programObject = new Program();

    static void Main(string[] args)
    {
        Program po = new Program();
        po.testing();
        Console.ReadLine();
    }

    void testing()
    {
        Console.WriteLine("Testing is working fine!!!");
    }
}

Best regards.

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