(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);
}
I would check the method TypeConverter.IsValid, although:
That means that if you don not use the try…catch by yourself you are going to convert twice the value.