I'm working with some legacy code right now which usually used try
+ catch
in combination with Convert.ToDecimal(someString)
(for instance) to try and convert strings to decimals. For some reasons I have to use the setting that - when debugging - I stop at every thrown exception (not only user-unhandled ones) and so this got annoying and I changed it to use TryParse
methods whenever possible.
Now I'm in a situation where there's an object
value and a target Type
, and all I want to know is if I can convert the value into the target type. Right now this is done as follows:
try
{
Convert.ChangeType(val, targetType);
}
catch
{
// Do something else
}
The actual result is not important and is not used further.
While this code is working right now, as I said, it gets a bit annoying and so I wonder: Is there another way of doing the above without having to catch an exception?
I thought of something like IsAssignableFrom
on a Type
, but this doesn't seem to be applicable in my case (I don't want to assign, I want to know if explicitly converting is possible).