# Convert string to integer or default

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;
}


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;
}
}

• I think the name ToInt32OrDefault was better ;-) – t3chb0t Oct 30 '15 at 5:26
• @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? – Helix Quar Oct 30 '15 at 8:09
• @BCdotWEB thanks for providing the link . it is more of style of writing code – paritosh Oct 30 '15 at 8:36
• 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. – christo8989 Oct 30 '15 at 17:29