Search code examples
c#parsingtypescasting

Given a Type and a String, can you try to convert the String to that Type without interogating the Type?


I have a List<Type> that represent a signature for a text based command from a custom scripting language. I am trying to determine how to parse a String[] to a List<object> where the object types correlate to the List<Type>. Basically given a Type t I would like to try to cast a String s to that Type.

So far I have this

Type t = ...;
String s = ...;
if(Convert.ChangeType(s, t) != null)
{

}

Which I doubt is correct after thinking about Convert.ChangeType more. It is meant to simply change the type of the given object, not "parse" it. Seeing as you can't simply do (double)"ImAString" I would assume this method would be used to convert between object types that are "directly" castable.

Is there any general solution to this? Or is the only way to do this to create a large switch on the given Type and parse within each case(Most likely missing Types in the switch in the future)?

EDIT: Further, the return type of ChangeType is object. I assume that if I were to do a retObjectFromChange is double would be true (assuming I changed the type to a double)?


Solution

  • Convert.ChangeType() will parse strings to numbers when possible, throwing an exception on strings that aren't valid numbers.

    Note: If you are going to convert between your own custom types a lot, you may want to use a TypeConverter instead. (TypeConverter will work better when converting both to-from primitive types like string.)

    See: Convert System.String generically to any complex type using "Convert.ChangeType()"

    EDIT: Yes, Convert.ChangeType("1.02", typeof(double)) is double should evaluate to true assuming no exceptions are thrown.