Overloading getter and setter causes a stack overflow in C#

I am not sure what is causing the StackOverflowException when I try to overwrite a get and set function. When I just use the default get and set it works.

enum MyEnumType
{
....
}

public MyEnumType data { get; set; }

But when I try to add additional data, it throws a StackOverflowException:

public MyEnumType data
{
  get
  {
    return data;
  }
  set
  {
    data = value;
  }
}

Any ideas? When I do this for ASP.NET user control attributes there isn’t any problem. Why is it is causing a StackOverflowException for a normal enum data type?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Yes, you do not have a backing field… this is how you should do it:

private MyEnumType data;

public MyEnumType Data
{
  get
  {
    return data;
  }
  set
  {
    data = value;
  }
}

What happens is that you are referring to the property to return itself, which causes an infinite loop of trying to access its own value. Hence, a stack overflow.

In your case when you do not add any additional logic in the get and set methods you could use an automatic property as well. This is simply defined like so:

public MyEnumType Data
{
  get;
  set;
}

Method 2

You are referencing the property itself inside your getter and setter, and that causes infinite recursion (a stack overflow). It would have been more obvious if you had used the standard naming conventions (Data).
Try something like:

private MyEnumType _data;

public MyEnumType Data
{
  get { return _data; }
  set { _data = value; }
}

Method 3

public class MyClass
{
    string propertyString;

    public string MyPropertyString
    {
        get
        {
            return propertyString;
        }
        set
        {
            propertyString = value;
        }
    }
}

The name of property must be different from the member name.

Method 4

Put a breakpoint inside the setter / getter and debug, making sure that you use step into (F11), not step over – this should help explain what’s going on.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x