2
\$\begingroup\$

I need my string-to-int converter to handle all exceptions without throwing any errors. I also have a use case where I need the default value to be less than zero if the TryParse is false.

  • Is there a built-in way of doing this?
  • Should I make any changes to the method?

public int ToInt32OrDefault(string value, int defaultValue = 0)
{
    int result;
    if (Int32.TryParse(value, out result) == false)
        result = defaultValue;

    return result;
}
\$\endgroup\$

1 Answer 1

7
\$\begingroup\$
  1. Use int rather than Int32

  2. You can write an inline expression rather than a multi-line statement

I would prefer to write an extension method here to wrap this method:

public static class IntExtension
{
    public static int ToInt32OrDefault(this string value,int defaultValue=0)
    {
        int result;
        return int.TryParse(value, out result) ? result : defaultValue;
    }
}
\$\endgroup\$
7
  • 1
    \$\begingroup\$ I think the name ToInt32OrDefault was better ;-) \$\endgroup\$
    – t3chb0t
    Oct 30, 2015 at 5:26
  • \$\begingroup\$ @paritosh It's not obvious to me why using 'int' is better than using 'Int32' especially if 'Int32' is retained in the function name. Is it a matter of style? \$\endgroup\$
    – Helix Quar
    Oct 30, 2015 at 8:09
  • 2
  • \$\begingroup\$ @BCdotWEB thanks for providing the link . it is more of style of writing code \$\endgroup\$
    – Paritosh
    Oct 30, 2015 at 8:36
  • 1
    \$\begingroup\$ In response to the style, I've been using the system type name for utility functions and the keyword for everything else. I like seeing the difference but maybe I'm the minority. \$\endgroup\$ Oct 30, 2015 at 17:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.