\$\begingroup\$
\$\endgroup\$
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
1 Answer 1
\$\begingroup\$
\$\endgroup\$
7
Use
int
rather thanInt32
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
-
1\$\begingroup\$ I think the name
ToInt32OrDefault
was better ;-) \$\endgroup\$t3chb0t– t3chb0t2015年10月30日 05:26:09 +00:00Commented 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– Helix Quar2015年10月30日 08:09:58 +00:00Commented 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\$BCdotWEB– BCdotWEB2015年10月30日 08:36:12 +00:00Commented Oct 30, 2015 at 8:36
-
\$\begingroup\$ @BCdotWEB thanks for providing the link . it is more of style of writing code \$\endgroup\$Paritosh– Paritosh2015年10月30日 08:36:35 +00:00Commented 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\$christo8989– christo89892015年10月30日 17:29:42 +00:00Commented Oct 30, 2015 at 17:29
lang-cs