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;


            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?

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

First: parsing

The shortest you can do is

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

Second: style


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).


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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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