User defined properties in C # throws a StackOverflowException when built

I was writing code in Unity3d engine and teaching myself C #. I tried to find an answer to my own question, but to no avail. I came from java and tried to use properties and I'm afraid I don't understand them very well. When I tried something like this:

public int Property
{
    get
    {
        return Property;
    }

    set
    {
        Property = value;
    }
}

      

I am getting a stack overflow initializing an object when that property is assignable. I was able to fix this simply by using the default property style:

get;
set;

      

but I don't know what happens in the first case throwing the exception. It would be great if someone could explain this.

+3


source to share


2 answers


You need a support box.

When you set this property, it will set itself, which will set itself, which will set itself, which will set itself, that ... you get the essence.

Or:

private int _Property;
public int Property
{
    get
    {
        return _Property;
    }

    set
    {
        _Property = value;
    }
}

      

or that:

public int Property
{
    get;
    set;
}

      

This last form, called an automatic property, creates this background field for you, so in fact the two will create almost the same code (the backing field name will be different)




If you do this in your version of the code:

x.Property = 10;

      

you get a property doing the same, and thus you get a stack overflow. You can rewrite it to a method with the same problem like this:

public void SetProperty(int value)
{
    SetProperty(value);
}

      

This tool will throw an exception for the same reason.

+12


source


Also, remember that when you create a property like

public class Example
{
   public String MyData{ get; set;}
}

      



Actually, when you compile it, the compiler translates it to something like this:

public class Example
{
   private String _myData;
   public String MyData{ get {return _myData}; set { _myData = value}}
}

      

+1


source







All Articles