An easy way is to use the IConvertible
interface:
static T ConvertStringTemplate<T>(string myString, IFormatProvider formatProvider = null)
{
formatProvider = formatProvider ?? System.Globalization.CultureInfo.CurrentCulture;
return (T)((IConvertible)myString).ToType(typeof(T), formatProvider);
}
If you want to restrict T
to a numeric type, the closest constraint you may use is the following one (from this answer ):
static T ConvertStringTemplate<T>(string myString, IFormatProvider formatProvider = null)
where T :
struct,
IComparable,
IComparable<T>,
IConvertible,
IEquatable<T>,
IFormattable
{
formatProvider = formatProvider ?? System.Globalization.CultureInfo.CurrentCulture;
return (T)((IConvertible)myString).ToType(typeof(T), formatProvider);
}
Usage:
var x = ConvertStringTemplate<int>("12"); // results in 12
[Edit]
As stated in comments, you probably wanted to use the current culture while converting the string, so I added an IFormatProvider
custom parameter to the method.