[ACCEPTED]-Why is a cast required for byte subtraction in C#?-byte

Accepted answer
Score: 16

Because subtraction is coercing up to an 3 integer. As I recall, byte is an unsigned 2 type in C#, so subtraction can take you 1 out of the domain of bytes.

Score: 11

That's because the result of a byte subtraction 1 doesn't fit in a byte:

byte - byte = (0..255) - (0..255) = -255..255
Score: 8

Arithmetic on bytes results in an int value by default.


Score: 4

Because arithmetic on bytes returns integers 10 by default so of the two possible assignments 9 the narrower type of zero (byte) is promoted 8 to int (that of oColor.r - percent). Thus 7 the type of the operation is an int. The 6 compiler will not, without a cast, allow 5 you to assign a wider type to a narrower 4 type, because it's a lossy operation. Hence 3 you get the error, unless you explicitly 2 say "I know I'm losing some data, it's fine" with 1 the cast.

Score: 2

This is because byte subtraction returns an 2 int. Actually any binary arithmetic operations 1 on bytes will return an int, so the cast is required.

Score: 2

Because arithmetic operations on sbyte, byte, ushort, and 7 short are automatically converted to int. The 6 most plausible reason for this is that such 5 operations are likely to overflow or underflow.

Thus, in 4 your ternary operation, the final oColor.R 3 - percent, actually results in an int, not 2 a byte. So the return type of the operation 1 is int.

Score: 1

Because the arithmetic expression on the 4 right-hand side of the assignment operator 3 evaluates to int by default. In your example 2 percent defaults to int. You can read more about 1 it on the MSDN page.

Score: 1

Try to run this C# code: object o = (byte)(1); o 11 = (int)o; What do you expect? Now try :)

I 10 think this is right:

Eric Lippert says, "I 9 don't think of bytes as "numbers"; I think 8 of them as patterns of bits that could be 7 interpreted as numbers, or characters, or 6 colors or whatever. If you're going to be 5 doing math on them and treating them as 4 numbers, then it makes sense to move the 3 result into a data type that is more commonly 2 interpreted as a number."

Perhaps byte is 1 closer to char than to int.

Score: 0

FWIW, java also promotes bytes to int.


More Related questions