C# Utility Class: CompundKey

C# Add comments

While working in C#, I’ve often found that I want to use more than one variable as a key to a Hashtable. I’ve abstracted this functionality into an object called CompundKey. CompoundKey allows one to combine any number of variables into a single object which, through proper implementation of Equals(), GetHashCode(), and ToString(), can be used as a key to any IDictionary or even System.Web.Caching.Cache.

Usage is very simple. For example:

IDictionary urlUserAccessTimes = new Hashtable();
CompoundKey urlUserKey = new CompoundKey(new Uri("http://www.deez.info/sengelha/", "Steven Engelhardt"));
urlUserAccessTimes[urlUserKey] = DateTime.Now;

Here’s the code:

CompoundKey code
/// <summary>
/// Creates a key for an IDictionary or a System.Web.Caching.Cache
/// out of a collection of values.
/// </summary>
/// <remarks>
/// Each value stored in CompoundKey must implement Equals()
/// correctly.
/// </remarks>
public struct CompoundKey
{
    private object[] m_keyParts;

    public CompoundKey(params object[] keyParts)
    {
        Debug.Assert(keyParts != null);

        m_keyParts = keyParts;
    }

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

        CompoundKey key = (CompoundKey) obj;
        return ArrayUtils.Equals(m_keyParts, key.m_keyParts);
    }

    public override int GetHashCode()
    {
        int hashCode = 0;
        foreach (object keyPart in m_keyParts)
        {
            if (keyPart != null)
            {
                hashCode ^= keyPart.GetHashCode();
            }
        }
        return hashCode;
    }

    /// <remarks>
    /// Unfortunately, System.Web.Caching.Cache uses strings as keys
    /// instead of objects.
    /// </remarks>
    public override string ToString()
    {
        StringBuilder sb = new StringBuilder();

        foreach (object keyPart in m_keyParts)
        {
            if (sb.Length > 0)
                sb.Append(",");
            sb.Append(keyPart != null ? keyPart.ToString() : "(null)");
        }

        return sb.ToString();
    }
}

Comments are closed.

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in