checked
and unchecked
statements specify the behavior when an overflow occurs. In a checked
context, OverflowException
is thrown whereas in unchecked
context, any high-order bits that cannot be accommodated by the destination type are discarded silently. Therefore, using unchecked
contexts may introduce pitfalls into your codebase unknowingly and should be avoided.
var sum = unchecked(list.Sum()); // `Sum()` invoked in an unchecked context
// Alternate scenario 1
var sum = list.Sum();
// Alternate scenario 2
try
{
var sum = checked(list.Sum());
} catch (OverflowException)
{
// Handle this case appropriately
}