Reading integers from AppSettings over and over

Viewed 29009

Some I do quite a lot of is read integers from AppSettings. What's the best way to do this?

Rather than do this every time:

int page_size; 
if (int.TryParse( ConfigurationManager.AppSettings["PAGE_SIZE"], out page_size){

}

I'm thinking a method in my Helpers class like this:

int GetSettingInt(string key) { 
  int i;
  return int.TryParse(ConfigurationManager.AppSettings[key], out i) ? i : -1;
}

but this is just to save some keystrokes.

Ideally, I'd love to put them all into some kind of structure that I could use intellisense with so I don't end up with run-time errors, but I don't know how I'd approach this... or if this is even possible.

What's a best practices way of getting and reading integers from the AppSettings section of the Web.Config?

ONE MORE THING...

wouldn't it be a good idea to set this as readonly?

readonly int pageSize = Helpers.GetSettingInt("PAGE_SIZE") doesn't seem to work.

4 Answers

I know that this question was asked many years ago, but maybe this answer could be useful for someone. Currently, if you're already receiving an IConfiguration reference in your class constructor, the best way to do it is using GetValue<int>("appsettings-key-goes-here"):

public class MyClass
{
    private readonly IConfiguration _configuration;

    public MyClass(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public void MyMethod()
    {
        int value = _configuration.GetValue<int>("appsettings-key-goes-here");
    }
}
Related