# Making the parsing of a String to an Int32 robust (valid, positive, not 0 validation)

I've a static method which parses a String (from the App.config) to a Int32. I need to have a valid (since the parsing would fail of course^^), positive and not zero integer. I've done it like this:

    public static int uiScale ()
{

int retint = 0;

try
{

retint = Int32.Parse(ConfigurationManager.AppSettings.Get("UiScale"));

}
catch (FormatException) {}
catch (OverflowException){}

return retint != 0 ? Math.Abs(retint) : 1;

}


This feels (don't ask me why) a little bit smelly I've to admit. Is this the best way to achieve this?

• use int.TryParse Oct 10 '16 at 12:57
• @t3chb0t Thanks! return int.TryParse(ConfigurationManager.AppSettings.Get("UiScale"), out retint) && retint != 0 ? Math.Abs(retint) : 1 ? Oct 10 '16 at 13:03

First: parsing

The shortest you can do is

int uiScale;
return
int.TryParse(ConfigurationManager.AppSettings.Get("UiScale")‌​, out uiScale)
&& uiScale!= 0 ? Math.Abs(uiScale) : 1 ;


Second: style

uiScale

This method should be called either GetUiScale or be a property if named UiScale because in C# we use PascalCase for public members and methods usually contain a verb (where it makes sense).

retint

Don't just call it like this. It's better to use the real name that better describes the purpose of the variable so uiScale would be fine.