I had a problem with TryParse working correctly for me. I have a list of values โโthat I'm pretty sure are valid (since they come from another component in our system), but I would like to make sure that there is proper error handling in place.
Here is an example of a list of my values:
20.00
20.00
-150.00
And here is the method I originally wrote:
private decimal CalculateValue(IEnumerable<XElement> summaryValues) { decimal totalValue = 0; foreach (XElement xElement in summaryValues) { decimal successful; Decimal.TryParse(xElement.Value, out successful); if (successful > 0) totalValue += Decimal.Parse(xElement.Value); } return totalValue; }
The variable "success" returned false for -150.00, so I added NumberStyles:
private decimal CalculateValue(IEnumerable<XElement> summaryValues) { decimal totalValue = 0; foreach (XElement xElement in summaryValues) { decimal successful; Decimal.TryParse(xElement.Value, NumberStyles.AllowLeadingSign, null, out successful); if (successful > 0) totalValue += Decimal.Parse(xElement.Value, NumberStyles.AllowLeadingSign); } return totalValue; }
However, now that I have NumberStyles, none of the numbers will be parsed! Iโm good that IFormatProvider is set to null, because thatโs all on our system. Does anyone see what I can do wrong?
Jeannine
source share