Endless loop in getter / setter c #

class Program { static void Main(string[] args) { something s = new something(); s.DoIt(10); Console.Write(s.testCount); } } class something { public int testCount { get { return testCount; } set { testCount = value + 13; } } public void DoIt(int val) { testCount = val; } } 

This is what I have because I wanted to test and play with getters / seters stuff for C #. However, I am getting a StackOverFlowException that was unhandled in "set {testCount = value + 13}". And I can not go through it, because I get the message "The debugger cannot continue the process. The process was completed" from Visual Studio. Any ideas what I'm doing wrong?

Edit: Today I found out that I did a pretty dumb derp. Given the many instant answers. Now I know better.

+4
source share
5 answers

You have infinite recursion because you mean a property in a property.

To do this, use the support field:

 private int testCount; public int TestCount { get { return testCount; } set { testCount = value + 13; } } 

Note the name of the TestCount property (which also conforms to the C # naming standard), as opposed to the name of the TestCount field (lowercase t ).

+17
source

You must declare a variable to return the property:

 class something { private int _testCount; public int testCount { get { return _testCount; } set { _testCount = value + 13; } } ... 
+4
source

You have a circular link in your recipient of the property. Try the following:

 class Something { private int _testCount; public int TestCount { get { return _testCount; } set { _testCount = value; } } public void DoIt(int val) { _testCount = val; } } 
+3
source

It:

 public int testCount { get { return testCount; } 

he returns himself, which forces him to fulfill himself.

Instead of returning your own property in yourself, save the specified value in another (preferably protected or private) variable. Then manipulate this variable both in the installer and in the receiver.

+2
source
 class Program { static void Main(string[] args) { something s = new something(); s.DoIt(10); Console.Write(s.testCount); } } class something { private int _testCount; public int testCount { // you are calling the property within the property which would be why you have a stack overflow. get { return _testCount; } set { _testCount = value + 13; } } public void DoIt(int val) { testCount = val; } } 
+1
source

Source: https://habr.com/ru/post/1482180/


All Articles