Reading config value to a proper data type

Automatic conversion of values from app.config

  • Share

Reading from application config is pretty easy in .NET. You literally need one line to fetch the value.

A minor but annoying problem is that configuration is always returning string value. You can always handle this string value in your code in case you need to convert, most probably to some value type. The following snippet takes any type that implements IConvertible and tries to convert string from config to required type.

        public static T GetSetting<T>(string key, T defaultValue = default(T)) where T : IConvertible
        {
            string val = ConfigurationManager.AppSettings[key] ?? "";
            T result = defaultValue;
            if (!string.IsNullOrEmpty(val))
            {
                T typeDefault = default(T);
                result = (T)Convert.ChangeType(val, typeDefault.GetTypeCode());
            }
            return result;
        }
    

In case it fails to convert you will get default value for the type you passed or you will get default value which you specify in the method call.

For example, assume that you have the following values in your app.config:

<configuration>
  <appSettings>
    <add key="boolVal" value="true"/>
    <add key="stringVals" value="123"/>
    <add key="intVal" value="4"/>
  </appSettings>
</configuration>
    

Example of reading bool value from the config

Console.WriteLine(GetSetting<bool>("boolVal"));
    

Example of reading int number value from config

Console.WriteLine(GetSetting<int>("intVal")   4);
    

You probably did not expect that string will make big issue, but it will. The reason for that is that string i actually reference type. This is because string value can be large, therefore can overflow the stack memory which is only 1MB. For that reason string was made as reference type and if you try to get default value of string type you will get null which is default value for all reference types.

for the same reason you cannot limit T to be struct since it will not allow string then and string is something that you in most of the cases will need from config.

The following example will crash because of null default value.

Console.WriteLine(GetSetting<string>("stringVal"));
    

To fix this thing, we need to check if the type T is specifically of string type and return String.Empty for this type as a defult value.

 public static T GetSetting<T>(string key, T defaultValue = default(T)) where T : IConvertible
        {
            string val = ConfigurationManager.AppSettings[key] ?? "";
            T result = defaultValue;
            if (!string.IsNullOrEmpty(val))
            {
                T typeDefault = default(T);
                if (typeof(T) == typeof(String))
                {
                    typeDefault = (T)(object)String.Empty;
                }
                result = (T)Convert.ChangeType(val, typeDefault.GetTypeCode());
            }
            return result;
        }
    

Attached is a sample console app to give this snippet a try. It's not something complex, but I found it really useful when reading from config or any other place which by default returns only string values

  • Share

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.

Comments for this article

comments powered by Disqus