Reading typed values from the ConfigurationManager appsettings

Here is a sample code that shows how to read values from the .NET appSettings section with auto conversion to the correct type or a fallback to a default value. Same can be applied to a registry


public static T AS<T>(string appsettingKey, T fallback = default)
{
    string val = ConfigurationManager.AppSettings[appsettingKey] ?? "";

    if (string.IsNullOrEmpty(val))
        return fallback;
    
    try
    {
        Type typeDefault = typeof(T);
        TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
        return converter.CanConvertFrom(typeof(string)) ? (T)converter.ConvertFrom(val) : fallback;
    }
    catch (Exception)
    {
    }

    return fallback;
}

...

bool isEnabled = AS("isEnabled", true);
int fontSize = AS("fontSize", 16);
...

Post a Comment

Previous Post Next Post