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

An unhandled exception of type 'System.StackOverflowException' occurred inC# ArrayList Search using Linq Extension OfType MethodHtml5 Doctype Headersystem.outofmemoryexception was thrownSystemOutOfMemoryException was thrown (mscorlib)Linq Anonymous TypesMembership ProviderC# read excel xlsx 2007C# Recursion ExampleWhat is the purpose of virtual keyboard on bank websitesJquery Radio Button CheckedJQuery Form With ValidationCheckbox Check all GridviewJQuery Radio Button CheckedC# Arraylist foreachtransactionasp net image uploadJQuery auto .focus()String was not recognized as a valid BooleanHTML5 TutorialJquery Dropdown Selected ValueASP.net File HandlingJQuery add/remove Class DynamicallyJQuery set .focus()Compiler Error Message CS0433Password HackIndex was outside the bounds of the arrayJQuery Ajax PostThe trust relationship between this workstation and the primary domain failedHTML5 Canvas AnimationGoogle JQuery CDN
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.

Tags:

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
Satalaj More+

I'm Satalaj.