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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Casting question 2
Round 3
using nullable types 1
enum with underlying type 1
nullable types 1
short res = shortA + shortB result in compiler error. Why? 10
Number type conversion 5
No operators defined on ushort 10

Top