I want to parse a string into a type easily, but I don\'t want to write wrapper code for each type, I just want to be able to do \"1234\".Parse() or the like and have it return
I know this question is four years old, but still you could consider using this:
public static T Parse<T>(this string target)
{
Type type = typeof(T);
//In case of a nullable type, use the underlaying type:
var ReturnType = Nullable.GetUnderlyingType(type) ?? type;
try
{
//in case of a nullable type and the input text is null, return the default value (null)
if (ReturnType != type && target == null)
return default(T);
return (T)Convert.ChangeType(target, ReturnType);
}
catch
{
return default(T);
}
}