Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StackOverflow error on instantiation

I'm getting a StackOverflow error whenever I instantiate this class in C#. Can anyone explain why?

class Money
{
    public Money(decimal value, Currency usedCurrency)
    {
        Value = value;
        UsedCurrency = usedCurrency;
    }

    public decimal Value
    {
        get { return Value; }
        set { Value = Math.Round(value, 2, MidpointRounding.ToEven); }
    }

    public Currency UsedCurrency;
}

public enum Currency
{
    USD,
    EUR,
    GBP,
    CAD,
    AUD
}

Here is an instantiation example :

var money = new Money(100, Currency.USD);
like image 851
poisonssting Avatar asked Mar 17 '14 15:03

poisonssting


2 Answers

Your property is referencing itself. When you try to get Value, it refers to Value... which tries to get Value again... and on and on.

public decimal Value
{
    get { return Value; }
    set { Value = Math.Round(value, 2, MidpointRounding.ToEven); }
}

Use a backing field. (Also, I'd rename your property to something more meaningful, especially since value has a special meaning.)

private decimal roundedCurrency;
public decimal RoundedCurrency
{
    get { return roundedCurrency; }
    set { roundedCurrency = Math.Round(value, 2, MidpointRounding.ToEven); }
}
like image 100
Grant Winney Avatar answered Nov 09 '22 21:11

Grant Winney


You need a backing field for your property Value. In your current code, get/set for the property are trying to set the property, thus introducing recursive calls and Stackoverflow exception.

private decimal _Value;

public decimal Value
{
    get { return _Value; }
    set { _Value = Math.Round(value, 2, MidpointRounding.ToEven); }
}
like image 32
Habib Avatar answered Nov 09 '22 21:11

Habib