views:

527

answers:

4

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 is no problem. I am wondering why it is causing a StackOverflowException for a normal enum data type.

+5  A: 

You are referencing the property itself inside your getter and setter, that causes infinite recursion (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; }
}
Henk Holterman
+14  A: 

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, this causes an infinite loop of trying to access its own value. Hence, StackOverFlow.

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;
}
Robban
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.
Matthew Scharley
That is correct, thanks for the clarification Matthew.
Robban
+3  A: 
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.

Ahmed Khalaf
A: 

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

Kragen