Generic Type-Safe Method to Retrieve Values from App Settings

Following my post from yesterday, I had to publish this little method that helps you retrieve values from your appSettings in a type-safe manner.

I simply love things like that – just a few lines of code make sure you won’t have to worry about type casting in the rest of your application!

using System;
using System.Configuration;

namespace MyApp.Domain.Helpers
{
	public static class ConfigHelper
	{
		public static T GetAppSetting<T>(string key)
		{
			var setting = ConfigurationManager.AppSettings[key];
			if (null == setting) return default(T);
			return (T)Convert.ChangeType(setting, typeof(T));
		}
	}
}

 
* Please note that this method will return the default value of type T if the setting key isn’t present, and throw an exception if the value is of an incorrect type. Other approaches to error handling might need to be implemented depending on your application.

And the usage:

var intValue = ConfigHelper.GetAppSetting<int>("IntValue");
var stringValue = ConfigHelper.GetAppSetting<string>("StringValue");

Leave a Reply

Your email address will not be published. Required fields are marked *