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

.net, byte, c#, casting, integer

Solution

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.

Problem

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?

Original source

Related problems