Search code examples
c#propertiesstack-overflow

StackOverflow exception on private properties field


Can someone please tell me why I get StackOverflowException for the code below ?

    private float _voltageRange
    {
        get { return _voltageRange + ((10F/100F)*_voltageRange); }
        set { _voltageRange = value; }
    }

How can I fix this problem? Isn't it taht compiler will make a backing field automatically?

What I want to achive is returning the _VoltageRange plus 10% of itself.


Solution

  • Both your getter and your setter call themselves recursively.

    No, the compiler doesn't create a backing field for you automatically - not unless you use an automatically implemented property like this:

    public float VoltageRange { get; set; }
    

    Whenever you provide getter/setter bodies, you have to do it all yourself.

    It sounds like you want:

    private float _voltageRange;
    private float VoltageRange
    {
        get { return _voltageRange + ((10F/100F)*_voltageRange); }
        set { _voltageRange = value; }
    }
    

    Or more simply:

    private float _voltageRange;
    private float VoltageRange
    {
        get { return (_voltageRange * 11) / 10; }
        set { _voltageRange = value; }
    }
    

    (Or just multiply by 1.1f, but that will have a little more possibility for data loss.)

    Note that this is a pretty odd property - one where the value set isn't the same one that's retrieved. Normally this:

    VoltageRange = VoltageRange;
    

    would be a no-op. That's what most readers would expect.

    It would probably be better to have two properties, like this:

    private VoltageRange { get; set; }
    
    private EffectiveVoltageRange { get { return VoltageRange * 1.1f; } }