Why is a cast required for byte subtraction in C#?
Solution 1
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.
Solution 2
That's because the result of a byte subtraction doesn't fit in a byte:
byte - byte = (0..255) - (0..255) = -255..255
Solution 3
Arithmetic on bytes results in an int value by default.
Solution 4
Because arithmetic on bytes returns integers by default so of the two possible assignments the narrower type of zero (byte) is promoted to int (that of oColor.r - percent). Thus the type of the operation is an int. The compiler will not, without a cast, allow you to assign a wider type to a narrower type, because it's a lossy operation. Hence you get the error, unless you explicitly say "I know I'm losing some data, it's fine" with the cast.
Solution 5
This is because byte
subtraction returns an int
. Actually any binary arithmetic operations on bytes
will return an int
, so the cast is required.
Billy
I am 9 foot 3 inches, 230 pounds and I enjoy fishing, hiking, long walks on the beach... Oh wait wrong website for that!
Updated on July 19, 2022Comments
-
Billy almost 2 years
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 typebyte
andbyte
is an integer type... then why do I need to have the cast? -
Charlie Martin about 15 yearsI think that's subtraction, actually....
-
Jhonny D. Cano -Leftware- about 15 yearsWhat a nice graphic explanation !!!
-
Adam Frisby about 15 yearsNeither does any integer type except floats or decimals. int is of finite range too, so (min_int - max_int) wont fit, but it returns an int.
-
Andrew Hare about 15 yearsIs there a reason for the downvote?
-
Charlie Martin about 15 yearsWasn't me, at least. I think we're having a random downvoter, I got one too.
-
dhara tcrails almost 9 yearsSubtraction can take you out of the domain of every number type. That doesn't really explain why there is no byte-specific subtraction operator.
-
Charlie Martin almost 9 yearsWell, then, the answer is "because the developers of C# decided they didn't want one."
-
chtenb over 6 yearsLink is dead...
-
Rafael Herscovici almost 6 years@Timothy Cartner, Link only answers are not recommended on SO, For the reason it stands now for a year, with a broken link. Could you provide some context?