I want to convert string to unsigned short. Example "123" equal to number 123 or 0x7B. But i get an error while doing the convertion : "Error 9 Cannot implicitly convert type 'int' to 'ushort'. An explicit conversion exists (are you missing a cast?)"

Here is my code:

        UInt16 usTest = 0;
            string sTest = "123";
            UInt16 usOne = 1;
            UInt16 usZero = 0;

            usTest = Convert.ToUInt16(sTest) + usOne;
            usTest = Convert.ToUInt16(sTest) + 1;
            usTest = Convert.ToUInt16(sTest) + Convert.ToUInt16(1);

All the 3 convertion above getting the same error message. Is there anyway to overcome this error?

So I wrote the code as below which is working. But I doesn't like it.....

            usTest = Convert.ToUInt16(sTest);

You have to typecast it explicitly,

            usTest = (UInt16)(Convert.ToUInt16(sTest) + usOne);
            usTest = (UInt16)(Convert.ToUInt16(sTest) + 1);
            usTest = (UInt16)(Convert.ToUInt16(sTest) + Convert.ToUInt16(1));

In C# all math done on integers is converted to Int32 if it is smaller than an Int32. As he said above, you have to explicitly cast them back into the size you want. And while the ++ operator looks like math, it doesn't treat it as math :)

Edited 4 Years Ago by Momerath

This question has already been answered. Start a new discussion instead.