Ross Coded Classes

June 17, 2008

Pop Quiz #1 Answer

Filed under: .NET Tips — Tags: , — Ross Bradbury @ 12:30 pm
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 Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: