I think this looks like a bug in the C# compiler.
Consider this code (inside a method):
const long dividend = long.MinValue;
const long divisor = -1L;
Console.WriteLine(dividend % divisor);
It compiles with no errors (or warnings). Seems like a bug. When run, prints 0
on console.
Then without the const
, the code:
long dividend = long.MinValue;
long divisor = -1L;
Console.WriteLine(dividend % divisor);
When this is run, it correctly results in an OverflowException
being thrown.
The C# Language Specification mentions this case specifically and says a System.OverflowException
shall be thrown. It does not depend on the context checked
or unchecked
it seems (also the bug with the compile-time constant operands to the remainder operator is the same with checked
and unchecked
).
Same bug happens with int
(System.Int32
), not just long
(System.Int64
).
For comparison, the compiler handles dividend / divisor
with const
operands much better than dividend % divisor
.
My questions:
Am I right this is a bug? If yes, is it a well-known bug that they do not wish to fix (because of backwards compatibility, even if it is rather silly to use % -1
with a compile-time constant -1
)? Or should we report it so that they can fix it in upcoming versions of the C# compiler?