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);
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); }
}
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); }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With