Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have to following code in VS2008 .net 3.5 using WinForms:

byte percent = 70;
byte zero = 0;

Bitmap copy = (Bitmap)image1.Clone();
...

Color oColor = copy.GetPixel(x, y);
byte oR = (byte)(oColor.R - percent < zero ? zero : oColor.R - percent);

When I leave the "(byte)" off the last line of code, I get a compiler error saying it "Cannot implicitly convert type 'int' to 'byte'." If everything is of type byte and byte is an integer type... then why do I need to have the cast?

like image 446
Billy Avatar asked May 29 '09 18:05

Billy


3 Answers

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

like image 150
Charlie Martin Avatar answered Oct 01 '22 13:10

Charlie Martin


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

byte - byte = (0..255) - (0..255) = -255..255
like image 20
schnaader Avatar answered Oct 01 '22 12:10

schnaader


Arithmetic on bytes results in an int value by default.

like image 30
Timothy Carter Avatar answered Oct 01 '22 14:10

Timothy Carter