Every project has a group of settings that can be used to configure a web site. Sometimes we store these in the web.config file and sometimes we store them in a database and typically what happens is you create a number of functions to read settings like:
public static string GetSetting_AsString(string settingKey) { /*...*/ }
public static string GetSetting_AsInt(string settingKey) { /*...*/ }
public static string GetSetting_AsBool(string settingKey) { /*...*/ }
This is boring and I finally got sick of copying and pasting all of these functions and decided to start living the Generics dream! With one simple function I have been able to replace all other generic functions with one beautiful one.
And here it is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public static class SettingRepository
{
public static T GetSetting<T>(string settingKey, T defaultValue )
{
if (string.IsNullOrEmpty(settingKey))
return defaultValue;
ProjectEntities dc = new ProjectEntities();
Setting setting = dc.Settings.Where(s => s.SettingKey == settingKey).FirstOrDefault();
if (setting == null)
return defaultValue;
return (T)Convert.ChangeType(setting.SettingValue, typeof(T));
}
}
This function gets a setting from a table named Setting in our database.
To retrieve strongly type settings is really easy.
public static void SettingRepositoryTest()
{
string stringSetting = SettingRepository.GetSetting("stringKey", "Default Value");
int intSetting = SettingRepository.GetSetting("intKey", 99);
bool boolSetting = SettingRepository.GetSetting("boolKey", true);
DateTime dateTimeSetting = SettingRepository.GetSetting("dateTimeKey", DateTime.Now);
}
Related posts:

Hello ,
Nice article.
I have my setting in a table.
Could you please send the the complete code for ProjectEntities for all the project ?
Regards,
@faris The Settings table I have uses the following schema
SettingId int IDENTITY(1,1) NOT NULL
SettingKey varchar(25) NOT NULL
DisplayName varchar(50) NULL
SettingValue varchar(50) NOT NULL