Invalid listing from 'System.String' to 'System.TimeSpan'

I currently have a generic method that reads a value from a database based on a key and returns a specific type of that value.

public T Get<T>(string key, T defaultValue) { var myparms = new List<SqlParameter> { new SqlParameter("@KEY", key), }; const string getPropertyQuery = "SELECT SPARM_VALUE FROM SYSPARAMS WHERE SPARM_KEY = @KEY;"; var returnedValue = //Get value from Database if (returnedValue == null) { return defaultValue; //Value does not exists so return default. } return (T)Convert.ChangeType(returnedValue, typeof(T)); } 

But when I try to return a TimeSpan type, I get the following exception. Invalid cast from 'System.String' to 'System.TimeSpan'.

After several searches, I found that the most common solution is to use the TimeSpan.Parse or TimeSpan.TryParse methods.

I also found the TimeSpan Structure.

public struct TimeSpan : IComparable, IComparable, IEquatable, IFormattable

My question is why, why is TimeSpan unable to do this. Is it because it does not have an IConvertible interface? Any thoughts on this would be greatly appreciated.

+8
c #
source share
3 answers

I don't think Convert.ChangeType is what you really want. Try TypeConverter.ConvertFrom :

 var converter = TypeDescriptor.GetConverter(typeof(T)); return converter.CanConvertFrom(returnedValue) ? (T)converter.ConvertFrom(returnedValue) : defaultValue; 
+22
source share

There is no explicit conversion / conversion defined between string and TimeSpan because most strings are not TimeSpan s.

If the framework defines such a composition, do you expect them to exist on DateTime and all other value types?

+1
source share

There is an implicit conversion between String and TimeSpan , you need to explicitly convert using Parse or TryParse

+1
source share

All Articles