Can someone explain to me what exactly is the checked an unchecked block ?
And when should I use each ?
Arithmetic overflow; for example:
int i = int.MaxValue -10;
checked {
i+= 20; // boom: OverflowException
// "Arithmetic operation resulted in an overflow."
}
So use checked
when you don't want accidental overflow / wrap-around to be a problem, and would rather see an exception.
unchecked
explicitly sets the mode to allow overflow; the default is unchecked
unless you tell the compiler otherwise - either through code (above) or a compiler switch (/checked
in csc).