Lonzo
Lonzo

Reputation: 2818

Overflow in C# expressions Ok?

In what way(s) would be an overflow in an expression be desirable in the following cases:

  1. Calculating a hash value
  2. Calculating a check sum

?

Upvotes: 0

Views: 124

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503859

So long as you're expecting that operations may overflow, and that the definition of what you're trying to do allows for overflow (or possibly requires it as a result) it makes life a lot easier.

For instance, one algorithm for calculating a hash is:

  • Start with a prime number
  • For each field in your object, multiply the current result by another prime number, and add the hash of the field

For example:

int ret = 37;
ret = ret * 37 + field1.GetHashCode() * 23;
ret = ret * 37 + field2.GetHashCode() * 23;
ret = ret * 37 + field3.GetHashCode() * 23;
return ret;

Here, any of the calculations could overflow, but that's okay - we're not really interested in the magnitude of the number, just the aim that it's likely to be different for different objects, but the same for equal ones.

Trying to do this without overflow is a pain - you could use XOR, but that has other downsides.

Upvotes: 4

Related Questions