12

The MSDN documentation for Interlocked.Increment states:

This method handles an overflow condition by wrapping: if location = Int32.MaxValue, location + 1 = Int32.MinValue. No exception is thrown.

What does “location + 1” mean in this context? If Increment alters the memory location next to the location field, isn't this likely to lead to corruption in the .NET runtime, given that this adjacent location could be anything (object references, class metadata, etc)?

Douglas
  • 53,759
  • 13
  • 140
  • 188
  • 1
    In this context, `location` is simply the name of an int variable. So saying `location + 1` is just a normal mathematical statement. – Glorin Oakenfoot Feb 22 '16 at 16:34
  • location + 1 is just a mathematical statement. `location = Int32.MaxValue` so location + 1 would overflow to `Int32.MinValue` – Jonathan Carroll Feb 22 '16 at 16:36
  • Yes, that makes more sense. (I've been reading too much pointer arithmetic.) Thanks to all for the clarification! – Douglas Feb 22 '16 at 16:38
  • 2
    It is a pretty uninspired name, the argument is actually a pointer. Thus "location". The *ref* keyword in C# ensures that a pointer is generated at runtime. The jitter directly translates the method to a single CPU instruction, LOCK XADD for x86 and x64, no runtime corruption can occur. – Hans Passant Feb 22 '16 at 16:46
  • I guess the name threw me off, along with the use of `=` to represent equality rather than assignment. I figured that I was probably missing something obvious. – Douglas Feb 22 '16 at 16:54

1 Answers1

12

It just means that if your value you want to increment is already equal to Int32.MaxValue and you increment by one, instead of throwing an error, it returns Int32.MinValue

That's the same what happens if you do

var value = Int32.MaxValue;
value += 1;

If you explicitly want an exception to be thrown, use the checked keyword

var value = Int32.MaxValue;
value = checked(value + 1);
MichaC
  • 13,104
  • 2
  • 44
  • 56
  • 9
    Just to mention that `value = checked(Interlocked.Increment(ref value));` does **not** throw an exception if value is int.MaxValue, it just sets it to int.MinValue – stuartd Feb 22 '16 at 17:02