I faced a "ridiculous" problem.
I was trying to convert a string to int16 (I am forced to do it in int16 and not in int32/integer).
My first thought was to try:
convertedVal = Convert.ToInt16(newVal)
which thrown an exception: Value was either too large or too small for UInt16.
But my string was "10", so it was between the minValue and the maxValue.
I solved my problem using :
convertedVal = Int16.Parse(newVal) 'TryParse works also
Although I solved my problem I haven't understand what I did wrong.
Could somebody explain to me why this happened?
Thanks for your time
This usually happens if there is an extra space on the string, so better Trim
it
convertedVal = Convert.ToInt16(newVal.Trim())
Both methods should be the same according to the MSDN page
Using the
ToInt16(String)
method is equivalent to passing value to theInt16.Parse(String)
method. value is interpreted by using the formatting conventions of the current thread culture.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With