What do the checked and unchecked keywords do in C#?
Quick Answer
By default, integer arithmetic in C# silently wraps around on overflow (int.MaxValue + 1 becomes a large negative number). A checked block/expression makes overflow throw OverflowException instead; unchecked explicitly restores the silent-wraparound behaviour. You can also set the project-wide default with CheckForOverflowUnderflow.
Normally in C#, if an int arithmetic operation overflows, it just wraps around silently — you get a nonsensical value with no warning, which has been the source of real security bugs. Wrapping the code in a checked block makes it throw OverflowException instead, so the bug surfaces immediately rather than corrupting data downstream. unchecked does the opposite, explicitly allowing the wraparound, which is occasionally intentional for things like hash computation. I reach for checked around arithmetic on values that come from outside the program, like a size calculated from user input, where silently wrapping would be dangerous.
checked { var x = int.MaxValue + 1; }throws; the same line unwrapped silently producesint.MinValue.- Constant expressions overflow-check at compile time regardless, unless wrapped in
unchecked. - Use
checkedaround arithmetic on untrusted or externally-derived sizes (array lengths, financial totals) where a silent wraparound would be a security or correctness bug. - Checked arithmetic has a small runtime cost — not worth it for every loop counter.