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)?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With