How Stack overflow exception occurs when property

2019-08-31 12:41发布

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?

3条回答
迷人小祖宗
2楼-- · 2019-08-31 12:50

In C#, property is a syntax sugar for pair of methods: get_PropertyName and set_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:

public string get_Name()
{
    return get_Name();
}

public void set_Name(string value)
{
    set_Name(value);
}

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.

查看更多
我想做一个坏孩纸
3楼-- · 2019-08-31 12:59

USE this

string _name;
public string Name{
   get{ return _name; }
   set{ _name=value; }
}

OR

public string Name{get;set;}
查看更多
老娘就宠你
4楼-- · 2019-08-31 13:05

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.

查看更多
登录 后发表回答