Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type casting needed for byte = byte - byte?

Tags:

c#

.net

c#-3.0

I have the following code:

foreach (byte b in bytes)
{
    byte inv = byte.MaxValue - b;
    // Add the new value to a list....
}

When I do this I get the following error:

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

Each part of this statement is a byte. Why does C# want to convert the byte.MaxValue - b to an int?

Shouldn't you be able to do this some how without casting? (i.e. I don't want to have to do this: byte inv = (byte) (byte.MaxValue - b);)

like image 211
Vaccano Avatar asked Apr 17 '10 04:04

Vaccano


1 Answers

According to the C# Language Reference:

because the arithmetic expression on the right-hand side of the assignment operator evaluates to int by default.

The reason for this could be because your processor is going to be faster at accessing a 4-byte memory address than a 1-byte memory address, so arithmetic operators are defined to work on 4-byte operands.

like image 69
Bill the Lizard Avatar answered Nov 02 '22 23:11

Bill the Lizard