I have a really simple function that I wrote about a million years back that tries to convert a string to another type. Works great for values types, numbers, enums, datetimes etc so I use it all the time when parsing xml file values, web request results - whatever.
However my code won't work on the Windows Phone 7 because the "TypeDescriptor" object is not implemented (see the PC code sample below). Any recommendations on how I can implement a really simple string -> type converter on the phone?
Here's my existing code (written for non-phones):
internal T ChangeType<T>(object o)
{
Type typeOfT = typeof(T);
// null
if (o == null)
{
return default(T);
}
// are types the same
if (typeOfT == o.GetType())
{
return (T)o;
}
// these are different type - try to see
// if there's a built in convertor
// NOTE: "TypeDescriptor" not implemented on Windows Phone 7
TypeConverter convertor = TypeDescriptor.GetConverter(typeOfT);
if (convertor.CanConvertFrom(o.GetType()))
{
return (T)convertor.ConvertFrom(o);
}
else
{
throw new Exception("Can not convert value to type: " + typeOfT.Name);
}
}