Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading getter and setter causes a stack overflow in C# [duplicate]

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?

like image 701
Nap Avatar asked Sep 17 '09 09:09

Nap


1 Answers

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;
}
like image 130
Robban Avatar answered Oct 18 '22 11:10

Robban