C# – Stack-overflow Exception

Stack-overflow Exception

The exception is triggered because of too many nested method calls. Each method call is kept on the stack memory. The program terminates because of infinite and uncontrolled recursion. Process terminated message is displayed with no recovery option also try-catch block will not be able to catch the exception.

One of the common place the exception happens is when setting the get and set methods in a class and forgetting to set the backing field. This happens because you are recursively calling the property again which creates infinite recursion at run time. This class will compile successfully but will throw exception during run time.
Example:

public class Data
  {
        public string MemberId { 
            get {return this._ID;}
            set { this._ID = value;}
        } 

        public string ALT_MEM { get; set; } 
  }

To solve this you will need to declare private backing field to hold the value.

Example:

public class Data
  {
        //You need to declare this to avoid stackoverflow exception
        private string _ID;

        public string MemberId { 
            get {return this._ID;}
            set { this._ID = value;}
        } 

        public string ALT_MEMBNO { get; set; } 


  }

If you are using the auto-property feature, it will create a hidden backing field so you don’t need to worry about it.

  
public string FirstName { get; set;}

Live as if you were to die tomorrow. Learn as if you were to live forever..
-Mahatma Gandhi