Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite loop in getter/setter c# [duplicate]

Tags:

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

Is what I have, because I was wanting to test and play around with the getters/setters stuff for C#. However, I get a StackOverFlowException was unhandled at "set { testCount = value + 13}". And I can't step through it, as I get a "The debugger cannot continue running the process. Process was terminated" message from Visual Studio. Any ideas what I'm doing wrong?

Edit: Today I've learned that I've done a pretty stupid derp. Given the multitudes of instant responses. Now I know better.

like image 207
Michael Fender Avatar asked May 22 '13 14:05

Michael Fender


3 Answers

You have an infinite recursion, as you are referring to the property in the property.

You should use a backing field for this:

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

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

like image 144
Oded Avatar answered Oct 14 '22 11:10

Oded


You should declare a variable to back the property:

class something
{
    private int _testCount;
    public int testCount
    {
        get { return _testCount; }
        set { _testCount = value + 13; }
    }
    ...
like image 38
Sina Iravanian Avatar answered Oct 14 '22 12:10

Sina Iravanian


You have a circular reference in your property's getter. Try this:

class Something
{
    private int _testCount;
    public int TestCount
    {
        get { return _testCount; }
        set { _testCount = value; }
    }

    public void DoIt(int val)
    {
        _testCount = val;
    }
}
like image 28
Alex Filipovici Avatar answered Oct 14 '22 12:10

Alex Filipovici