I am working with some legacy code right now that used try + catch in conjunction with Convert.ToDecimal(someString) (for example) to try to convert strings to decimal numbers. For some reason, I have to use a parameter that - when debugging - stops with every exception (not just custom unhandled ones), and therefore it is annoying, and I changed it to use TryParse methods TryParse possible.
Now I am in a situation where there is an object value and a Type target, and all I want to know is if I can convert the value to the target type. Now this is done as follows:
try { Convert.ChangeType(val, targetType); } catch { // Do something else }
The actual result is not important and is no longer used.
While this code is working right now, as I said, it is a little annoying, and so I wonder: Is there any other way to do this without catching the exception?
I thought of something like IsAssignableFrom in Type , but that doesn't seem to apply in my case (I don't want to assign, I want to know if explicit conversion is possible).
source share