Search code examples
c#stack-overflow

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");
    }
  }
}

Solution

  • 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.