2023-09-24 19:40:41
Source StackOverflow. Credit to: McGarnagle and Andrew Morton
checked
is a block keyword that enables arithmetic overflow checking. Normally, if an integer operation exceeds the maximum or minimum value that the type can handle, the operation proceeds anyway, and the result just cycles like an odometer.
And since there's a compiler option /checked
, which turns compiler checking on by default, there is also the unchecked
keyword which prevents overflow checking.
As far as usage, overflow checking should be used sparingly, as is true of exception handling in general. To check for an overflow at runtime, it's significantly faster (like, an order of magnitude) to do a simple check, rather than to turn on overflow checking:
int multiply(int i, int j) { if ((long)i * (long)j > int.MaxValue) throw new InvalidOperationException("overflow"); return i*j; }
You can do this even for Int64/long, using BigInteger (this can be still at least an order of magnitude faster than using checked):
long multiply(long i, long j) { if (new System.Numerics.BigInteger(i) + j > long.MaxValue) throw new InvalidOperationException("overflow"); return i*j; }