I'm reading about how to force an operation to throw an overflow exception, and on the "try it yourself" section, I had it in a different place than the book. I'm curious if there's a performance issue associated with one spot or the other, as I'm not certain the underlying mechanics of the checked
keyword.
The example in the book was doing a factorial, which will quickly throw an overflow, even with an unsigned long. This is the code that I came up with:
static long Factorial (long number) {
long result = 1;
for (int i = 2; i <= number; i++) {
checked {
result *= i;
}
}
return result;
}
However, looking at the answer page in the back of the book, they had the checked
wrapped around the entire body of the function, including the return
and long result = 1;
. Obviously you'll never need one in those places, so if anything, I would just wrap the for
loop in the check
.
Is the presence of it inside the loop causing some underlying CLR code to be generated repeatedly? (Like why you declare a variable before entering a for loop.) Or is there no overhead having it inside the loop?