2009-08-27

Strongly typed AppSettings with defaults

Very often I want configurable options for miscellaneous settings; but I hate to shift my focus from the code I'm working on to add a new AppSetting. Sometimes these settings are essential but more often than they are just options that I may need.

So the solution I like to use is to make default values for such AppSettings. If the service you are writing needs to retry a database or web service call a few times, why not make that option configurable but use a default of 5. The method below will grab an AppSetting & try to convert it. If it fails, it uses the default. Plus the generic T can be a value or reference type.


public static T GetAppSetting<T>(string key, T defaultValue)
{
if (String.IsNullOrEmpty(ConfigurationManager.AppSettings[key])) return defaultValue;

try
{
return (T)Convert.ChangeType(ConfigurationManager.AppSettings[key], typeof(T));
}
catch
{

}

return defaultValue;
}

// Sample Usage
public void DoSomething()
{
if(GetAppSetting("ShouldRun", true))
{
for(int i = 0; i < GetAppSetting("NumberOfTries", 5); i++)
{
if(SomeMethodSucceeds()) break;
}
}
}

No comments: