GetHashCode Method Immutability

Problem
You want to know if it’s okay that the value returned by an overridden GetHashCode method changes.

Solution
No, it’s not okay. The value returned by the method must not change over the object’s lifetime.

Comments
There are a couple of things you can do to ensure the hash value of an object doesn’t change. You can combine the hash codes of two or more immutable fields and return a constant value. Or, you can evaluate a random value at conception and store it in a private field. You’ll want to avoid calling the Object.GetHashCode method when overriding GetHashCode. Rather, evaluate the hash code by combining the values and hash codes of fields.

Example

public class Account {
    // These values are immutable after the object has been created.
    // They would be properties in a real-world app.
    public readonly string Name;
    public readonly string Type;

    private int hashCode;

    public Account(string name, string type) {
        this.Name = name;
        this.Type = type;
        // Accounts with the same name and type also have identical hash codes.
        // Use bitwise XOR to avoid overflow.
        hashCode = name.GetHashCode() ^ type.GetHashCode();
    }

    public override int GetHashCode() {
        return hashCode;
    }
}

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