Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error Trying to Parse a Generic Type whenType is TimeSpan

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'.

like image 297
Matt Wilko Avatar asked Oct 31 '25 00:10

Matt Wilko


1 Answers

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
like image 107
Marc Gravell Avatar answered Nov 03 '25 21:11

Marc Gravell