3
    <appSettings>
        <!-- Settings file for website! -->
        <add key="DefaultCookieExpiryMins" value="30" />
    </appSettings>

Why do I have to set everything as a string? Why can't I have different datatypes in there like int to help me stop having to cast everything?

Tom Gullen
  • 61,249
  • 84
  • 283
  • 456
  • 1
    Write a wrapper class, so you only need to cast once – citronas Mar 25 '11 at 17:37
  • 1
    Text files only contain strings. What do you want to be different? Either you will be casting it as an `int` in code, or you'd I guess add something like `type="int"` to the web.config? But since nothing would stop you from typing in whatever you want into a text file, even if you could add a data type to a setting, it seems rather pointless. You can still have bad data. It's still going to break somewhere if you don't validate the data when you get it from the config file. – Jamie Treworgy Mar 25 '11 at 20:05

2 Answers2

6

This is why I prefer custom configuration sections over just putting key/value pairs in appSettings. See this MSDN article for more information on how to make your own configuration section. Once you have your own configuration section class, you should be able to access your settings as any data type you'd like.

Jacob
  • 77,566
  • 24
  • 149
  • 228
0

I just use generics for things like this.

public static T GetConfigurationValue<T>(string keyName)
        {
            if (System.Configuration.ConfigurationManager.AppSettings[keyName] != null)
            {
                T result;
                try
                {
                    result = (T)Convert.ChangeType(System.Configuration.ConfigurationManager.AppSettings[keyName], typeof(T));
                }
                catch
                {
                    return default(T);
                }

                return result;
            }

            throw new ArgumentException("A key with the name " + keyName + " does not exist in the current configuration.", keyName);
        }

Usage: GetConfigurationValue<int>("DefaultCookieExpiryMins");

Scott
  • 13,735
  • 20
  • 94
  • 152