C# Convert values

Date: 2016-03-19

Source: http://stackoverflow.com/questions/6884653/how-to-make-a-generic-type-cast-function

public static T ConvertValue(T def, object input)
{
	if (input != null)
	{
		var converter = TypeDescriptor.GetConverter(typeof(T));
		if (converter != null)
		{
			string convert = "";
			if (input is IConvertible)
			{
				convert = ((IConvertible)input).ToString(System.Globalization.CultureInfo.InvariantCulture);
			}
			else
			{
				convert = input.ToString();
			}

			return (T)converter.ConvertFromString(null, System.Globalization.CultureInfo.InvariantCulture, convert);
		}
	}
	return def;
}

public static T ConvertValue(U value) where U : IConvertible
{
    return (T)Convert.ChangeType(value, typeof(T));
}
1280cookie-checkC# Convert values