Feeds:
Posts
Comments

Archive for December, 2008

Calculating Hash Codes

I don’t know about you, but I find overriding Equals to be a pita.  Why?  Because if you override Equals, you also must override GetHashCode, and that’s just no fun. 😉

ReSharper evidently will generate GetHashCode for you, according to this stackoverflow entry.  That’s all find and dandy (if you use R#), but the code is a tad bit ugly if you’ve got to modify it.  Not that it’s not very understandable, it’s just a lot to have to type out for each field that should participate in the calculation of the hash code.  So, I got to thinking about whether a helper might not make this easier.  Here’s what I came up with.  Let me know what you think about this idea.

public struct HashCode
{
    private readonly int value;

    internal HashCode(int value)
    {
        this.value = value;
    }

    public static HashCode From<T>(T value)
    {
        return new HashCode(value.GetHashCode());
    }

    public HashCode And<T>(T other)
    {
        int hash = this.value;
        unchecked
        {
            hash = (hash * 397) ^ other.GetHashCode();
        }

        return new HashCode(hash);
    }

    public override bool Equals(object obj)
    {
        if (!(obj is HashCode))
        {
            return false;
        }

        return this == (HashCode)obj;
    }

    public override int GetHashCode()
    {
        return this.value;
    }

    public static bool operator ==(HashCode left, HashCode right)
    {
        return left.value == right.value;
    }

    public static bool operator !=(HashCode left, HashCode right)
    {
        return left.value != right.value;
    }
}

Usage is something like this:

public override int GetHashCode()
{
    return HashCode.From(firstField).And(secondField).GetHashCode();
}

I think that should be much easier to maintain.

Advertisements

Read Full Post »