About Me

My photo
Kozyatağı, İstanbul, Türkiye

Saturday, March 9, 2013

.NET Dictionary with Class Types as Key Type


In .NET, Dictionary<Tkey, Tvalue> class provides a hashed collection which improves the performance of read operations.

In most cases, type of the key element is a primitive type like int, string, long, etc. However in some scenarios, type of the key element needs to be a custom class that we implement.

In such cases, the programmer is responsible for generating “smooth” hash code and compare equality. So here, do you think programmer needs to write a “hash code generator algorithm” and dwell upon minimizing collision of generated indices?


Here is a neat implementation:
In the class, we already know the members which provide equality and we also know that each of them has GetHashCode() method.  By invoking the GetHashCode() method on each of them and by joining them, we can solve the problem of generating hash code complexity.

The operation that I mentioned as “joining hash codes” is generally implemented as applying bitwise Exclusive OR (XOR) against hash codes because it provides even distribution of generated indices.


C# Code:
class Item
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public override bool Equals(object obj)
        {
            Item other = (Item)obj;
            return this.Id == other.Id &&
                   this.Name == other.Name;
        }

        public override int GetHashCode()
        {
            return Id.GetHashCode() ^ Name.GetHashCode();
        }
    }

For all the instances of Item class who has equal values for both Id and Name properties, the equal hash codes will be generated and they will be treated as same "key" by .NET dictionary.

No comments:

Post a Comment