C# arithmetic follows operand types rather than the result you expect: byte addition yields an int, integer division drops the fraction, and checked only guards its own textual scope. The article spells out each rule with small examples on .NET 10 and C# 14.
Key points
- Binary arithmetic on byte or short promotes to int, so the result type differs from the operands.
- Integer division rounds toward zero; casting the quotient to double afterwards cannot restore the lost fraction.
- Remainder takes the sign of the left operand, so % on negative values is not mathematical modulo.
- Integral and decimal division by zero throw DivideByZeroException, while double yields infinity or NaN instead.
- checked and unchecked act textually: wrapping a call in checked does not change the callee's arithmetic.
- int.MinValue divided by -1 throws ArithmeticException even unchecked; constant expressions are checked by default.
Real-world use
- Counting full batches or complete pages where a whole-number quotient is the intended result
- Ratio calculations that need a fractional result, so an operand must be converted before dividing
- Normalizing a possibly negative index into a nonnegative position without relying on % alone
This summary was generated by the agent from the original post on Nick Cosentino (Dev Leader). The full text and all rights belong to its author and publisher. Go to original