What are checked and unchecked contexts in C#?
Quick Answer
By default, integer arithmetic that overflows wraps silently (int.MaxValue + 1 becomes int.MinValue). A checked block/expression makes overflow throw OverflowException; unchecked forces the wrapping behaviour. You can also flip the default project-wide with <CheckForOverflowUnderflow>.
If an integer calculation overflows, C# by default just wraps around — int.MaxValue + 1 silently becomes the most negative int, no error. A checked block makes that throw an OverflowException instead, and unchecked forces the wrapping. For something like a money calculation or a counter that must never silently go wrong, I'd enable checked arithmetic for the whole project or wrap the specific code in checked. unchecked is intentional in places like hash code combination where you want the overflow.
- Silent overflow is a real bug source in financial/counting code — turn on checked arithmetic for those projects, or wrap the calculation in
checked { }. uncheckedis used deliberately for hash-code combination and bit manipulation where wrapping is expected.- Constant expressions are checked at compile time regardless.
- Doesn't affect floating point (which uses infinity/NaN, not exceptions).