I have the following code that I am using to try and parse a string to a generic type. In the instance I am using it fails when I try and parse to a TimeSpan. The input string is "12:34" which Parses fine using TimeSpan.Parse but I couldn't find a solution to implement <Generic>.Parse
Public Function ParseGeneric(Of T)(ByVal stringValue As String) As T
    Return DirectCast(Convert.ChangeType(stringValue, GetType(T)), T)
End Function
Error: Invalid cast from 'System.String' to 'System.TimeSpan'.
If you'll excuse some C#, TypeDescriptor / TypeConverter can help here:
static T ParseGeneric<T>(string stringValue)
{
    return (T)TypeDescriptor.GetConverter(typeof(T))
                 .ConvertFromString(stringValue);
}
If I had to guess (completely untested) the VB for that:
Public Function ParseGeneric(Of T)(ByVal stringValue As String) As T
    Return DirectCast(TypeDescriptor.GetConverter(GetType(T)) _
                .ConvertFromString(stringValue), T)
End Function
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With