appSettings, type-safety and default values — all in 5 minute’s work

Posted by Seth on October 27th, 2006

I recently wanted to have a method I could call to get a type-safe AppSetting, with an optional default value if the AppSetting wasn’t set. In C# 2.0, I came up with this:
public static T GetSetting<T>(string name, T defaultValue)
{
string input = ConfigurationManager.AppSettings[name];
if (input != null)
{
return (T)Convert.ChangeType(input, typeof(T));
}
else
{
return defaultValue;
}
}

Related posts

Using Enums to drive DropDownLists

Posted by Seth on October 1st, 2006

Mark came up with an idea to use Enums to drive lookups. I told him I could go one better by providing user-friendly names instead of programmer-friendly enum value names. The idea is to loop through the literal fields of the enum type and check for a DescriptionAttribute on each field. Anyway, here’s the source, with caching for top performance.

Related posts


Copyright © 2008 Seth Yates. All rights reserved.