ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

FromAppSettings

Get a value from AppSettings section of Web.Config and change its type to the correct one or return a default value in case the key doesn't exists.

Source

public static T FromAppSettings<T>(this string key, T defaultValue = default(T)) where T : IConvertible
{
	if (string.IsNullOrWhiteSpace(key))
		return defaultValue;

	var value = ConfigurationManager.AppSettings[key];

	if (string.IsNullOrWhiteSpace(value))
		return defaultValue;

	var tc = Type.GetTypeCode(typeof(T));

	switch (tc)
	{
		case TypeCode.Boolean:
		case TypeCode.Byte:
		case TypeCode.DateTime:
		case TypeCode.Decimal:
		case TypeCode.Double:
		case TypeCode.Int16:
		case TypeCode.Int32:
		case TypeCode.Int64:
		case TypeCode.String:
			T output;
			try
			{
				output = (T)Convert.ChangeType(value, tc);
			}
			catch
			{
				output = defaultValue;
			}

			return output;

		default:
			throw new NotSupportedException();
	}
}

Example

//Example 1
var email = "EMail".FromAppSettings(string.Empty);

//Example 2
var email = "EMail".FromAppSettings("noreply@extensionmethod.net");

//Example 3
var id = "AppID".FromAppSettings(int.MinValue);

Author: Adrián Maillo

Submitted on: 10 nov 2014

Language: C#

Type: Generic

Views: 4916