Does (ushort + ushort) return an int value?

J

JuLiE Dxer

Perhaps, I skipped over learning this particular tidbit.

I ran across an odd error while trying to add to ushort variables
together and assigning it to a 3rd ushort variable.

I get this compiler error:

error CS0029: Cannot implicitly convert type 'int' to 'ushort'


code is basically this


ushort u1, u2, u3;

u1 = 3;
u2 = 5;

u3 = u1 + u2;



Does ushort math always an int object?
 
J

Jon Skeet [C# MVP]

JuLiE Dxer said:
Perhaps, I skipped over learning this particular tidbit.

I ran across an odd error while trying to add to ushort variables
together and assigning it to a 3rd ushort variable.

I get this compiler error:

error CS0029: Cannot implicitly convert type 'int' to 'ushort'

code is basically this

ushort u1, u2, u3;

u1 = 3;
u2 = 5;

u3 = u1 + u2;

Does ushort math always an int object?

Sort of. In fact, you can't do maths with ushorts. What you *can* do
maths on is ints, and that's what happens with the above. You've
effectively got:

u3 = (int)u1 + (int)u2;

The only integer addition operators defined are:

int operator +(int x, int y);
uint operator +(uint x, uint y);
long operator +(long x, long y);
ulong operator +(ulong x, ulong y);

The normal (and somewhat long-winded) operator overload resolution is
applied to select the first of these as the best overload, and that's
the one which is used.
 
T

Tom Porterfield

pontifikas said:
try
u1 = (ushort)1;
u2 = (ushort)2;

Nope, see Jon Skeet's answer as to why that won't work. The following
would work:

ushort u1, u2, u3;
u1 = 3;
u2 = 5;

u3 = (ushort)(u1 + u2);
 

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

Top