Casting question

A

AMP

Hello,
I have:
ushort length= 4;
ushort len;
And I get an error here:
length = len + 4;

Error 6 Cannot implicitly convert type 'int' to 'ushort'. An explicit
conversion exists (are you missing a cast?)

Thanks Mike
 
?

=?ISO-8859-1?Q?Arne_Vajh=F8j?=

AMP said:
And I get an error here:
length = len + 4;

Error 6 Cannot implicitly convert type 'int' to 'ushort'. An explicit
conversion exists (are you missing a cast?)

Try:

length = (ushort)(len + 4);

Arne
 
J

Jon Skeet [C# MVP]

AMP said:
Hello,
I have:
ushort length= 4;
ushort len;
And I get an error here:
length = len + 4;

Error 6 Cannot implicitly convert type 'int' to 'ushort'. An explicit
conversion exists (are you missing a cast?)

Basically, there's no operator which adds two ushorts together - they
just get promoted to ints and then the addition is performed, resulting
in an int.

You'll need to cast the result, as Arne says.

However, if you can use += instead, you don't need the extra cast:

ushort x = 5;
ushort y = 10;

x += y;
 

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


Top