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?
In C#, property is a syntax sugar for pair of methods:
get_PropertyName
andset_PropertyName
(if the property is read-only or write-only, the corresponding method won't be generated). Your code will be converted by the compiler like this:Look at the getter and setter, and you'll see pure recursion. So, every time you'll try to access the property (no matter, for getting or for setting), you'll call recursive method.
USE this
OR
When you make the getter's code
{return Name;}
, you are recursing. How? When some code wants to get the value ofName
, 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
.