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;
}
BCdotWEB
11.4k2 gold badges28 silver badges45 bronze badges
asked Oct 30, 2015 at 2:08
\$\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;
 }
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
answered Oct 30, 2015 at 4:30
\$\endgroup\$
7
  • 1
    \$\begingroup\$ I think the name ToInt32OrDefault was better ;-) \$\endgroup\$ Commented 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\$ Commented Oct 30, 2015 at 8:09
  • 2
    \$\begingroup\$ "As a matter of style, use of the keyword is favored over use of the complete system type name." \$\endgroup\$ Commented Oct 30, 2015 at 8:36
  • \$\begingroup\$ @BCdotWEB thanks for providing the link . it is more of style of writing code \$\endgroup\$ Commented 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\$ Commented Oct 30, 2015 at 17:29

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.