Search code examples
c#propertiesstack-overflow

How Stack overflow exception occurs when property sets value to Itself


Stack overflow exception is the .NET exception (error) that is thrown when the limited memory available for the execution stack is exhausted. This is almost always caused by an infinite recursion, which ultimately results in too many nested method calls.

The following code will throw a stack overflow exception when trying to set a value.

  public String Name
  {
      get{return Name;}
      set{Name = value;}
  }

I know the references are stored in stack(here its Name) and Objects are stored in Heap(String Object). How excessive memory usage is happening at this place? Can anybody tell me whats happening behind the scene(The internal implementation details)? What is the necessity of a backing field?


Solution

  • When you make the getter's code {return Name;}, you are recursing. How? When some code wants to get the value of Name, your getter method just tells it, "Why don't you try asking me again?" See a problem? When you try getting a value, it'll tell you that you need to ask itself again. And again. And again!

    Every time the property is accessed and the getter is called, a new entry is added to the stack. Since this code will only tell other code to keep trying over and over, the stack infinitely become more occupied! (Every time you call a method, like your getter, an entry is added to the stack)

    Also, your updated question asks why the setter would cause a stack overflow. It's pretty much the same reason as before; when Name's setter is called, it calls itself. Simple quote to explain? Name says in response to your code, "If you want to set my value, try setting my value again?"

    Where does it do that? In Name = value;. You would try setting the value, but your method would tell it to set itself again. And again. And again.

    How can we fix that? As the other answerer showed, you can create another variable that will store the actual content. For example, Name will contain the getters and setters to successfully manipulate data. It won't store it in itself though, to avoid infinite recursion. It'll store it in another variable, like _Name.