14

For example:

int value = Int32.MaxValue;

unchecked
{
    value += 1;
}

In what ways would this be useful? can you think of any?

MasterMastic
  • 20,711
  • 12
  • 68
  • 90
  • 1
    It should be noted that `unchecked` is the default, so it is superfluous, unless you enabled `checked` mode. [The docs](http://msdn.microsoft.com/en-us/library/vstudio/74b4xzyw.aspx) say: *The `checked` keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions. By default, [..] if the expression contains one or more non-constant values, the compiler does not detect the overflow.* – Evgeniy Berezovsky Nov 20 '13 at 03:41

1 Answers1

25

Use unchecked when:

  • You want to express a constant via overflow (this can be useful when specifying bit patterns)
  • You want arithmetic to overflow without causing an error

The latter is useful when computing a hash code - for example, in Noda Time the project is built with checked arithmetic for virtual everything apart from hash code generation. When computing a hash code, it's entirely normal for overflow to occur, and that's fine because we don't really care about the result as a number - we just want it as a bit pattern, really.

That's just a particularly common example, but there may well be other times where you're really happy for MaxValue + 1 to be MinValue.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194