8
\$\begingroup\$

This feels wrong:

private decimal ConvertStringToDecimal(string decimalString, decimal defaultReturnValue)
{
    var returnDecimal = defaultReturnValue;

    try
    {
    returnDecimal = decimal.Parse(decimalString.Trim());
    }
    catch (Exception)
    {
    // naughty
    }

    return returnDecimal;
}

but I think this is the only way to transform a string from a third party system to a decimal whilst returning a default. Does anyone have any suggestions on how to improve this?

\$\endgroup\$

2 Answers 2

12
\$\begingroup\$

The easiest and most clean way would be to use decimal.TryParse() like so

private decimal ConvertStringToDecimal(string decimalString, decimal defaultReturnValue)
{
    decimal result;
    if (decimal.TryParse(decimalString.Trim(), out result))
    {
        return result;
    }

    return defaultReturnValue;
}  

Using exceptions to control the returned value isn't a good way, especially if there are better methods to use.

Your indentation is off but I assume that thats a posting issue.

\$\endgroup\$
4
  • \$\begingroup\$ oh yeah - forgot about that method (-: \$\endgroup\$ Commented Dec 21, 2015 at 13:14
  • \$\begingroup\$ I really don't understand why they did it this way, Java also uses exceptions for flow control when converting to numeric values. It's comforting that c# has a better alternative. Hopefully Java will “borrow” this method in the next version :) \$\endgroup\$ Commented Dec 21, 2015 at 16:52
  • \$\begingroup\$ @Morgen I have mixed feelings about the out parameter, it feels so low level... \$\endgroup\$ Commented Dec 21, 2015 at 18:38
  • 2
    \$\begingroup\$ @Caridorc I agree, still much better than throwing an exception as you don't incur the cost of building a stack trace every time the user gives you a malformed number. Returning a Maybe/Option type would be even better. \$\endgroup\$ Commented Dec 21, 2015 at 18:45
3
\$\begingroup\$

You can write the equivalent shorter, using the ternary operator ?: and decimal.tryParse, like this:

private decimal ConvertStringToDecimal(string decimalString, decimal defaultReturnValue)
{
    decimal value = decimal.TryParse(decimalString, out value) ? value : defaultReturnValue;
    return value;
}
\$\endgroup\$
0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.