Overloading Getter and Setter calls StackOverflow in C #

I'm not sure what causes a StackOverflowException when I try to overwrite the get and set function. When I just use the default value and its setting 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 this raises a StackOverflowException for the regular enum data type.

+4
source share
4 answers

Yes, you do not have a support field ... so you should do this:

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

What happens is that you refer to the property to return itself, it causes an infinite loop of attempts to access its own value. Therefore, StackOverFlow.

In your case, when you do not add additional logic to the get and set methods, you can also use the auto property. It is simply defined like this:

 public MyEnumType Data { get; set; } 
+25
source

You refer to the property itself inside your receiver and setter, which causes infinite recursion ( stack overflow ). This would be more obvious if you used standard naming conventions (data).
Try something like:

 private MyEnumType _data; public MyEnumType Data { get { return _data; } set { _data = value; } } 
+6
source
 public class MyClass { string propertyString; public string MyPropertyString { get { return propertyString; } set { propertyString = value; } } } 

The property name must be different from the principal name.

+3
source

Place the breakpoint inside the setter / receiver and debug, making sure that you use the step in (F11), do not go over - this should help explain what is happening.

0
source

All Articles