An unhandled exception of type 'System.StackOverflowException' occurred in

Here is a program that generates following exception.

An unhandled exception of type 'System.StackOverflowException' occurred in.

using System;
using System.Text.RegularExpressions;

namespace Csharp.StackOverFlowException.Example
{
  class Program
  {
    static void Main(string[] args)
    {

        y obj = new y();
      
      Console.ReadLine();

    }
  }

    public class x
    {
        y obj = new y();
        public x()
        {
            Console.WriteLine("X");
        }
    }

    public class y
    {
        x obj = new x();
        public y()
        {
            Console.WriteLine("Y");
        }
    }

  
   
  
}

Description:

When you try to instantiate an instance of class Y, the program first tries to initialize the object of class X where it tries instantiate an instance of Y.

This goes to infinite loop till there is no space available on Stack.

Note: It is myth that when you instantiate the object the constructor of class get called first.

Truth is that first it initializes the variables. In above case when you instantiate object of Y, program tries to initialize variable of type X.

Currently rated 3.9 by 9 people

  • Currently 3.888889/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5