Ross Coded Classes

Programming tips with no rose colored glasses.

Pop Quiz #1 Answer

You want to read the question first.
 
In this case, the bug in the code has to do with overflow exceptions.  The value of the GetHashCode() method that all objects have can return any Int32 value, ideally there is no less chance that it returns Int32.MaxValue or Int32.MinValue than the chance that it will return a smaller number like 5.  Doing arbitrary math with the result of GetHashCode() when the code is compiled as checked can easily cause an OverflowException.
 
Even if the code were unchecked and the wrapping behavior was expected and desired, it is still not clear to someone reading the code that you want it do that.

// Throws System.OverflowException if
// ServiceName.GetHashCode() is large enough.
public override int GetHashCode()
{
      return ServiceName.GetHashCode() + DbId;
}

// Explicitly decide to let the overflow wrap
public override int GetHashCode()
{
      unchecked
      {
            return ServiceName.GetHashCode() + DbId;
      }
}

// Shorter way to explicitly let the overflow wrap
public override int GetHashCode()
{
      return unchecked(ServiceName.GetHashCode() + DbId);
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.