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


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.


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;
				output = (T)Convert.ChangeType(value, tc);
				output = defaultValue;

			return output;

			throw new NotSupportedException();


//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: 3419