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

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:

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 Checked

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.
 

I'm Satalaj.