mj82
mj82

Reputation: 5263

Test if string can be converted to other, various type

(SOLVED) I'm building an application that can create some of its control dynamically, based on some description from XML file.
What I need now is something very similar to TryParse() method: a possibility to check (wihtout throwing/catching exception), if a text in string variable can be converted (or parsed) to a type, which name I have in other variabe (myType).
Problem is that myType can be any of .NET types: DateTime, Bool, Double, Int32 etc.

Example:

string testStringOk = "123";
string testStringWrong = "hello";
string myType = "System.Int32";

bool test1 = CanCovertTo(testStringOk, myType);      //true
bool test2 = CanCovertTo(testStringWrong, myType);   //false

How does CanCovertTo(string testString, string testType) function should look like?

The closest I get is following code:

private bool CanCovertTo(string testString, string testType)
{
    Type type = Type.GetType(testType, null, null);
    TypeConverter converter = TypeDescriptor.GetConverter(type);

    converter.ConvertFrom(testString);  //throws exception when wrong type
    return true;
}

however, it throws an exception while trying to convert from wrong string, and I prefer not to use try {} catch() for that.


Solution:

private bool CanCovertTo(string testString, string testType)
{
    Type type = Type.GetType(testType, null, null);
    TypeConverter converter = TypeDescriptor.GetConverter(type);
    return converter.IsValid(testString);
}

Upvotes: 6

Views: 3862

Answers (3)

James
James

Reputation: 82096

Instead of passing in the type as a string you should make use of generics e.g.

public bool CanConvert<T>(string data)
{
    TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
    return converter.IsValid(data);
}

Usage

bool test1 = CanConvert<Int32>("1234"); // true
bool test2 = CanConvert<Int32>("hello"); // false

Upvotes: 6

David Chandler
David Chandler

Reputation: 398

If they are just built-in .NET types, you can do the conversion based on a System.TypeCode. You could store the typecode in your XML (or convert your type string to a TypeCode) and do something like:

switch (code)
{
    case TypeCode.Boolean:
        bool.TryParse(value, out result);
        break;
    case TypeCode.Int32:
        int.TryParse(value, out result);
    ...
}

Upvotes: 0

Teudimundo
Teudimundo

Reputation: 2670

I would check the method TypeConverter.IsValid, although:

Starting in .NET Framework version 4, the IsValid method catches exceptions from the CanConvertFrom and ConvertFrom methods. If the input value type causes CanConvertFrom to return false, or if the input value causes ConvertFrom to raise an exception, the IsValid method returns false.

That means that if you don not use the try...catch by yourself you are going to convert twice the value.

Upvotes: 7

Related Questions