Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top