I have the need to examine to see if an object can be converted to a specific DataType or not, and came up with this :
public static bool TryParseAll(System.Type typeToConvert, object valueToConvert)
{
bool succeed = false;
switch (typeToConvert.Name.ToUpper())
{
case "DOUBLE":
double d;
succeed = double.TryParse(valueToConvert.ToString(), out d);
break;
case "DATETIME":
DateTime dt;
succeed = DateTime.TryParse(valueToConvert.ToString(), out dt);
break;
case "INT16":
Int16 i16;
succeed = Int16.TryParse(valueToConvert.ToString(), out i16);
break;
case "INT":
Int32 i32;
succeed = Int32.TryParse(valueToConvert.ToString(), out i32);
break;
case "INT32":
Int32 i322;
succeed = Int32.TryParse(valueToConvert.ToString(), out i322);
break;
case "INT64":
Int64 i64;
succeed = Int64.TryParse(valueToConvert.ToString(), out i64);
break;
case "BOOLEAN":
bool b;
succeed = Boolean.TryParse(valueToConvert.ToString(), out b);
break;
case "BOOL":
bool b1;
succeed = bool.TryParse(valueToConvert.ToString(), out b1);
break;
}
return succeed;
}
I'm wondering is there any ways other than this? Which is more dynamic and more efficient?
Thanks!
Here is my version of generic
TryParse
method. I believe you can use this version too:You should use the TypeDescriptor class:
of course this will throw an exception if the conversion fails so you will want to try/catch it.
I have combined both DmitryG's and RezaRahmati's suggested solutions: