Why does C# define Byte+Byte=Int32 instead of Byte+Byte=Byte like VB?
+1
A:
Because adding two very large bytes can overflow, and that's not normally what you want to happen.
Joel Coehoorn
2010-08-07 21:02:31
yeah, but adding two ints also can overflow, yet int+int = int, not long.
SWeko
2010-08-07 21:05:36
Bytes are much more likely to overflow than integers
Matt Greer
2010-08-07 21:07:50
@SWeko - it can, but only for unusually large magnitude integers. Probabilistically, C# makes a good guess at where bugs are likely to be caught.
Daniel Earwicker
2010-08-07 21:09:17
@SWeko: Good point. Though you can do checked arithmetic. Not sure why the automatic byte arithmetic conversion would be on by default, rather than requiring you do a "checked" block, and only detecting an overflow, without converting types.
Merlyn Morgan-Graham
2010-08-07 21:09:20
@Daniel, actually sum of two bytes can go up to 2*byte.MaxValue, and sum of two ints can go to 2*int.MaxValue, so the probability is about the same :)
SWeko
2010-08-07 21:13:57
@SWeko - only theoretically. Practically, it's much rarer to have ints that approach MaxValue. Also, the corresponding check for int (int+int=long) would cause all kinds of conversion problems in most programs that byte doesn't run into. If you're doing sums with bytes, a lot of the time you assign the result to an int anyway. If you're doing sums with ints, you usually still expect an int.
Joel Coehoorn
2010-08-07 21:23:40
In real world, of course that it's more common to have 250 of something and get 10 more (byte overflow) than to have 2147483640 and add 10. There is a similar logic that proves that about 1/4 of the numbers start with 1. However, that does not change the probabilities :) Moreover, I seldom work with bytes, but when I do, I'm well aware of their range, so my personal preference would be for operations on bytes to result in a byte, not in an int.
SWeko
2010-08-08 00:10:03
If you were really concerned about overflows, then why doesn't it widen to a Int16 instead of jumping all the way to an Int32?
Jonathan Allen
2010-08-08 04:59:45
@Joel, the only time I ever do sums of bytes is when working with an API that expects a byte. I can't imagine using it any other time.
Jonathan Allen
2010-08-08 05:01:27
*"However, that does not change the probabilities :)"* - In that case, the "probabilities" you're talking about seem to be unrelated to the real world. Ask yourself what would be most helpful given our commonsense prior knowledge about the distribution of integer values in most real programs. All language features are chosen in that way: assuming what is *most likely* to help. Most `int` values (say, discrete measurements in pixels, or counters) are way smaller than a billion, whereas `byte` values can be expected to span the available range much more evenly.
Daniel Earwicker
2010-08-08 08:45:08