There are many ways of doing this(listed by priority, specific to the OP's problem)
Option 1: Straight approach - Create multiple functions for each type you expect rather than having one generic function.
public static bool ConfigSettingInt(string settingName)
{
return Convert.ToBoolean(ConfigurationManager.AppSettings[settingName]);
}
Option 2: When you don't want to use fancy methods of conversion - Cast the value to object and then to generic type.
public static T ConfigSetting<T>(string settingName)
{
return (T)(object)ConfigurationManager.AppSettings[settingName];
}
Note - This will throw an error if the cast is not valid(your case). I would not recommend doing this if you are not sure about the type casting, rather go for option 3.
Option 3: Generic with type safety - Create a generic function to handle type conversion.
public static T ConvertValue<T,U>(U value) where U : IConvertible
{
return (T)Convert.ChangeType(value, typeof(T));
}
Note - T is the expected type, note the where constraint here(type of U must be IConvertible to save us from the errors)