-
Descriptionwhen adding (and probably performing other math operations on) small numbers (e.g. byte, short) a cast is required as the addition is done using the int add operator. that cast is not necessary with big numbers (e.g. int, long) because they have their own add operator. that cast is optimized away later in the process so it will not effect performance but it will be looking like it would to new developers. Reproduction Steps
byte ByteAddition(byte a, byte b)
{
return (byte)(a + b);
}
int IntAddition(byte ai, byte bi)
{
return ai + bi;
}
ByteAddition(1, 2);
IntAddition(3, 4);
Expected behaviorif the code is anyway exactly the same a cast wont be necessary. Actual behaviora cast is necessary. Regression?no, it was not different in past versions Known Workaroundsas stated above the actual executed code is exactly the same only the syntax is a bit misleading Configuration.net 8 Other informationa good solution will probably be just making the the operators from from |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
According to the C# specification, a Byte plus a Byte produces an Int32, hence why the cast is necessary. |
Beta Was this translation helpful? Give feedback.
-
As the answer mentions, there's a rule in the C# language that byte values (and sbytes, shorts, etc) are converted to ints before adding. Imagine for a second that this was not the case. In this alternate universe, when you write: byte a = 100;
byte b = 200;
Console.WriteLine(a + b); you would get the output Even worse, this would behave the same way, yielding 44 or throwing: int c = a + b; This overflow behavior happens with much smaller numbers for So, in this alternate universe, it would have become best practice to always cast smaller integer types to |
Beta Was this translation helpful? Give feedback.
Maybe, but it was an intentional design choice and one that was made probably 25 years ago. So at this point the behavior cannot be changed. The language team thought that it was more important to avoid accidental overflow on uncommon integral types than it was to achieve syntactic consistency.