0

I'm using TypeConverter.ConvertFromInvariantString in order to convert strings into concrete types.

Some conversions fail via and exception, and I would like to know about the failure before trying to convert.

Code example that will fail:

var tc = TypeDescriptor.GetConverter(typeof(int));
var val = tc.ConvertFromInvariantString("1.5");

Code that I'd wan't to have:

var canConvert = CanConvert(tc, "1.5", typeof(int));
if(canConvert)
{
   var val = tc.ConvertFromInvariantString("1.5");
   ......
}

I prefer not to use a try\catch block as a solution as I wan't to get a list of properties prior to the operation.

I've noticed the CanConvertFrom method that doesn't really work (It returns false when converting a float to double while the TypeConverter.ConvertFromInvariantString method succeeds).

So, is there a way to determine if I can convert the string into the type prior to the conversion?

Amir Popovich
  • 29,350
  • 9
  • 53
  • 99

0 Answers0