Search code examples
c#castingtype-conversionstring-conversion

Check conversion of type string to other types


I am using reflection and I want to do conversion checking for exception handling.

I need to check if string can convert to unknown type in my project.

I used :

TypeConverter t = TypeDescriptor.GetConverter(typeof(string));
            Console.WriteLine(t.CanConvertTo(typeof(int)));

but it returns false !

or even this one returns false again :

StringConverter stringConverter = new StringConverter();
            Console.WriteLine(stringConverter.CanConvertTo(typeof(int)));

my quesion is that why StringConverter returns false for converting string to int ???

EDIT :

I use this code to convert string to unknown types : ( result is string )

resultCastedToTargetPropertyType = Convert.ChangeType(result,propertyInfo.PropertyType);

Solution

  • Oddities of the implementation of CanConvertFrom aside, in your context you wouldn't get much help by knowing that a certain conversion could be performed until you try it. A converter cannot give you a definitive answer based on the type alone, for the same reason that there is no single answer to the question "can a string be converted to integer": the answer is "it depends on the string" - i.e. string "123" can be converted to int, while strings "hello" and "1234567891011121314151617181920" cannot be converted to int.

    In other words, the answer could be obtained only when you know the value being converted. In your case it means putting try/catch block around your call of Convert.ChangeType, and interpreting each of the four exceptions it could throw (reference).