Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 320
mj82 Avatar asked Nov 22 '11 12:11

mj82


2 Answers

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.

like image 105
Teudimundo Avatar answered Sep 19 '22 01:09

Teudimundo


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
like image 31
James Avatar answered Sep 22 '22 01:09

James