C# checked block

Yochai Timmer picture Yochai Timmer · Mar 7, 2011 · Viewed 7.8k times · Source

Can someone explain to me what exactly is the checked an unchecked block ?
And when should I use each ?

Answer

Marc Gravell picture Marc Gravell · Mar 7, 2011

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).