# using UInt16

S

#### Sergei Shelukhin

I am doing some manipulations with UInt16s and I know what I'm doing,
however the result of every calculations is int and I get tons of
Error Cannot implicitly convert type 'int' to 'ushort'. An explicit
conversion exists (are you missing a cast?)
in ridiculous places like (not the actual code)
UInt16 a, b;
....
b = a + 1; // error!
if ( a > 5 )
{
a -= 2; // error!
}

I know theoretically UInt16 might overflow, but so can int,
theoretically. I know what I'm doing and that UInt16 will not, in
fact, overflow (all input and calculations are checked on case by case
basis, as opposed to stupid blank errors that do not really guarantee
anything).

How do I get rid of this errors?

A

#### Alberto Poblacion

Sergei Shelukhin said:
How do I get rid of this errors?

It would be nice if addition and substraction returned a ushort when all
of their operands were of type ushort but, alas, they return an int, so an
explicit cast is needed in order to assign it to a ushort.

ushort a=0, b;

b = (ushort)(a + 1);
if ( a > 5 )
{
a = (ushort)(a-2);
}

A

#### Alan

I am doing some manipulations with UInt16s and I know what I'm doing,
however the result of every calculations is int and I get tons of
Error   Cannot implicitly convert type 'int' to 'ushort'. An explicit
conversion exists (are you missing a cast?)
in ridiculous places like (not the actual code)
UInt16 a, b;
...
b = a + 1; // error!
if ( a > 5 )
{
a -= 2; // error!

}

I know theoretically UInt16 might overflow, but so can int,
theoretically. I know what I'm doing and that UInt16 will not, in
fact, overflow (all input and calculations are checked on case by case
basis, as opposed to stupid blank errors that do not really guarantee
anything).

How do I get rid of this errors?

Unless you're relying on the wraparound behavior of a UInt16 (in which
case you should be using unchecked() in the arithmetic), just do your
calculations as int, then cast it to UInt16 or ushort at the end when
you actually need the value.

-- Alan
-- cleartopartlycloudy.blogspot.com