Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to int16

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

like image 983
Nianios Avatar asked Nov 01 '12 11:11

Nianios


2 Answers

This usually happens if there is an extra space on the string, so better Trim it

convertedVal = Convert.ToInt16(newVal.Trim())
like image 130
John Woo Avatar answered Sep 20 '22 02:09

John Woo


Both methods should be the same according to the MSDN page

Using the ToInt16(String) method is equivalent to passing value to the Int16.Parse(String) method. value is interpreted by using the formatting conventions of the current thread culture.

like image 39
bendataclear Avatar answered Sep 18 '22 02:09

bendataclear