Click here to Skip to main content
12,241,419 members (46,417 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


32 bookmarked

Dictionary with a Custom Key

, 13 Feb 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
An article on creating a custom key to use with a dictionary.


Generic dictionaries are great, but sometimes the built-in data types just doesn't suffice as keys. Perhaps you want to use more than one value as key, or a data type that doesn't support comparing by default.


Luckily, the .NET Framework is built in a way that easily allows expansion. By creating a class to use as key, and a comparer that the dictionary uses to compare the key values, you can put anything you like in the key.

The Key Class

First, let's create a class to use as key in a dictionary. As an example I will use a dictionary that will keep track of cars parked in a parking garage. The parking spaces are identified by a floor number and and parking space number for that floor, so the key will have two integer properties; floor and parkingSpace:

public class ParkingSpaceKey {

    private int _floor, _parkingSpace;

    public ParkingSpaceKey(int floor, int parkingSpace) {
        _floor = floor;
        _parkingSpace = parkingSpace;


So far all you can do with the class is to create instances of it, but we will add a comparer to it so that we can use it with a dictionary.

The Comparer

The IEqualityComparer<T> interface is used to implement a comparer for a dictionary. It has two methods that you need to implement: Equals and GetHashCode.

The Equals method is used to compare two key values. It simply returns true if the values are equal.

The GetHashCode method returns a hash code value for a specific key value. The hash code is what the dictionary uses to divide all the items in the dictionary into buckets. That is what gives speed to the dictionary.

There is a lot you can read about how you create good hash keys, but there are just two things that you need to know to make a hash code that works reasonably well in most situations:

  1. The method must always return the same hash code for a specific key value.
  2. The hash codes should be evenly distributed, so that you get as many buckets as possible in the dictionary.

Let's look at two examples of implementations. The first just returns the same value all the time:

public int GetHashCode() { return 0; }

This fulfills the rule that a specific key value always gets the same hash code, so the hash code actually works. The distribution of the hash codes is terrible, though. The dictionary would only get a single bucket to store all items in.

The second implementation is the actual implementation of the GetHashCode method for the System.Int32 structure:

public int GetHashCode() { return this; }

The hash code for an integer is actually the integer itself, which satisfies the rule that the hash code is always the same for a value. When it comes to distribution, it does not only work, it's actually the ideal implementation. Every key value will get it's own bucket in the dictionary, so you will always have as many buckets as possible. (It's of course only possible to make an ideal implementation if the key doesn't contain more than 32 bits of data, as the hash code contains 32 bits of data. If you have more data in the key, some key values have to share the same hash code.)

Implementing the Comparer

For our parking space example, we will just take the two integer values and do an exclusive or between them to create a hash code. Perhaps not the best implementation possible, but certainly good enough for this example.

Now, let's create a class that implements the IEqualityComparer<T> interface, and put it in the ParkingSpaceKey class. By putting the comparer inside the key class, you get two advantages. It's obvious what the class does, and you have access to the private variables in the key class from the comparer class.

public class ParkingSpaceKey {

    private int _floor, _parkingSpace;

    public ParkingSpaceKey(int floor, int parkingSpace) {
        _floor = floor;
        _parkingSpace = parkingSpace;

    public class EqualityComparer : IEqualityComparer<ParkingSpaceKey> {

        public bool Equals(ParkingSpaceKey x, ParkingSpaceKey y) {
            return x._floor == y._floor && x._parkingSpace == y._parkingSpace;

        public int GetHasCode(ParkingSpaceKey x) {
            return x._floor ^ x._parkingSpace;



That's all it takes to make a custom key for a dictionary. There are no properties for reading the values that are stored in the key. You can add them if you like, but that isn't needed to use the class as a key. The comparer doesn't care what the key contains, it only needs to be able to compare key values and to get a hash code for a key.

Use the Custom Key Class

Now you can use the comparer when you create a dictionary:

Dictionary<ParkingSpaceKey, Car> garage = new Dictionary<ParkingSpaceKey, Car>(
    new ParkingSpaceKey.EqualityComparer());

It's crucial that you actually remember to create an instance of the comparer for the dictionary. Otherwise the dictionary will use the default way of comparing the key objects, which will be comparing the references. (That means that even if you create a key with the same values as a key in the dictionary, it can't be used to find it as they are separete object so they doesn't have the same reference.)

To use the dictionary, you simply create a key object with the values you need to access. Example:

ParkingSpaceKey key = new ParkingSpaceKey(4, 42);
if (garage.ContainsKey(key)) {
    Console.WriteLine("Parking space occupied.");
} else {
    Console.WriteLine("Parking space available.");

That all, folks.


Wikipedia: hash table
MSDN Library: IEqualityComparer interface
MSDN Library: Dictionary class

Points of Interest

I learned about this when I needed dictionaries to cache data for a web application. Some of the data is depending on several different variables, so I needed dictionaries with custom keys.




About the Author

Web Developer Byt Bil Nordic AB
Sweden Sweden
A programmer with things like Atari BASIC, 6502 machine code, Compis Pascal, GFA Basic, 68000 assembler, Turbo Pascal, 80x86 assembler, ASP (VBScript) and VB6 in the baggage.

Currently employed to build applications mainly using ASP.NET (C#) and MS SQL Server.

You may also be interested in...

Comments and Discussions

QuestionType in code example Pin
Heinz Kessler15-Aug-13 21:58
memberHeinz Kessler15-Aug-13 21:58 
GeneralMy vote of 5 Pin
Mikhail Tsennykh (devnoob)7-Mar-12 6:51
memberMikhail Tsennykh (devnoob)7-Mar-12 6:51 
GeneralMy vote of 4 Pin
cdguenther28-Apr-11 13:21
membercdguenther28-Apr-11 13:21 
GeneralThanks! Pin
Z.J.Liu19-Nov-09 15:00
memberZ.J.Liu19-Nov-09 15:00 
GeneralError in compilation Pin
rkb20-Feb-08 11:16
memberrkb20-Feb-08 11:16 
GeneralRe: Error in compilation Pin
rkb20-Feb-08 11:38
memberrkb20-Feb-08 11:38 
AnswerRe: Error in compilation Pin
Guffa20-Feb-08 12:24
mvpGuffa20-Feb-08 12:24 
Generala few suggestions Pin
BillWoodruff18-Feb-08 16:14
memberBillWoodruff18-Feb-08 16:14 
GeneralNice article Pin
MaxGuernsey18-Feb-08 13:00
memberMaxGuernsey18-Feb-08 13:00 
Generalnon-generics Pin
tack000018-Feb-08 12:03
membertack000018-Feb-08 12:03 
AnswerRe: non-generics Pin
Guffa19-Feb-08 0:10
mvpGuffa19-Feb-08 0:10 
For a non-generic collection you would implement the non-generic IEqualityComparer interface, which requires you to implement the Equals and GetHashCode methods only.

Despite everything, the person most likely to be fooling you next is yourself.

GeneralThis is good Pin
N a v a n e e t h14-Feb-08 23:11
memberN a v a n e e t h14-Feb-08 23:11 
GeneralGood Article Pin
merlin98114-Feb-08 4:57
membermerlin98114-Feb-08 4:57 
GeneralRe: Good Article Pin
Guffa14-Feb-08 9:24
mvpGuffa14-Feb-08 9:24 
GeneralKeyedCollection Pin
Scott Dorman13-Feb-08 17:37
mvpScott Dorman13-Feb-08 17:37 
GeneralRe: KeyedCollection Pin
Guffa13-Feb-08 21:17
mvpGuffa13-Feb-08 21:17 
Generalstruct vs. class Pin
Marc Clifton13-Feb-08 9:37
protectorMarc Clifton13-Feb-08 9:37 
GeneralRe: struct vs. class Pin
Guffa13-Feb-08 10:18
mvpGuffa13-Feb-08 10:18 
GeneralRe: struct vs. class Pin
Marc Clifton13-Feb-08 10:40
protectorMarc Clifton13-Feb-08 10:40 



| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160426.1 | Last Updated 13 Feb 2008
Article Copyright 2008 by Guffa
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid