Translation of the question What is the C# “checked” keyword for? in SOin
I just found this keyword for the first time. What does it do and when should it be used?
int multiply(int i, int j)
{
return checked(i * j);
}
Translation of the question What is the C# “checked” keyword for? in SOin
I just found this keyword for the first time. What does it do and when should it be used?
int multiply(int i, int j)
{
return checked(i * j);
}
checked
is a block that allows arithmetic overflow, normally, if an integer operation exceeds the maximum or minimum value that the type can handle, the operation is processed anyway, and the result simply changes like an odometer.For example:
Placing the above snippet in a block
checked
will prevent the overflow, and instead fire aOverflowException
Taking into account that there is a compiler option that activates "checking" by default, there is also a block
unchecked
, which prevents overflow checking.Usage-wise, overflow checking should be used sparingly, as is the case with exception handling in general. To check for an overflow at runtime, it's significantly faster (about an order of magnitude) to do a simple check, rather than triggering the overflow check:
This can be done even for Int64/long, using
BigInteger
Please anyone feel free to make corrections/modifications to the translation.