6

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?

1
  • 4
    Your recursively calling your public getter (in the getter)! That's why you get a stack overflow. Commented Sep 17, 2009 at 9:58

4 Answers 4

31

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

For those who don't know, C# implements properties under the hood as two seperate functions . Hence, each call to a setter or getter introduces another stack layer, eventually leading to a stack overflow.
8

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; }
}

Comments

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.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.