Dictionaries in C#: The Hashtable

About a week ago I began talking about collections in C#, and discussed two special cases, the Stack and the Queue. Another group of specialized collection classes are dictionaries. Dictionaries operate off of a key / value system, where you lookup your information, your value, based on a key you create. The key can be a string, number or other type of data, but it must be unique within the dictionary. Just like in your traditional printed dictionary, you can’t have two entries for the same key.

The most basic type of Dictionary is the Hashtable. The hashtable has the basic functionality for putting entries into the dictionary collection, getting a value based on a key, looping through them, and updating or removing them.

Getting data into the hashtable is pretty easy. First make sure to include a using reference to System.Collections, then simply create a hashtable variable, and finally call the Add method, passing in the key and value.  

      Hashtable myHash = new Hashtable();

 

      myHash.Add(“ArcaneCode”, “arcanecode.wordpress.com”);

 

To read or update the data stored in the value, you can treat the hashtable as if it were a simple array, using the key where you’d normally put the index.

 

      Console.WriteLine(myHash[“ArcaneCode”]);

      myHash[“ArcaneCode”] = “Here I’ve changed the value.”;

      Console.WriteLine(myHash[“ArcaneCode”]);

 

      Console.Read();

 

Hashtables are great for storing data where you have a good primary key you can quickly reference things by. In our example, I’ve stored strings as the value part of the key / value pair, but you can use any type of object for the value, including classes you create.

The examples so far assume you will always want to retrieve a single item out of your hashtable. However, we all know there are times when you will want to iterate over the entire collection. To do this, it’s necessary to understand how your key / value pair is storied.

In keeping with the spirit of OOP, what is actually stored in the hashtable collection is another object of type DictionaryEntry. The dictionary entry object has two essential properties, the Key and the Value, both of which are the generic object type. Here’s an example of how to loop over the myHash collection.

      // Clear out the previous items

      myHash.Clear();

 

      // Now add some new items.

      // Note we use an int as the key this time.

      myHash.Add(1, “Item one”);

      myHash.Add(2, “Item two”);

      myHash.Add(3, “Item three”);

 

      // Loop over the list, writing out the value

      foreach (DictionaryEntry myEntry in myHash)

      {

        Console.WriteLine(myEntry.Value);

      }

 

      Console.Read(); // Wait for user to press a key

 

Note we cycle through a list of DictionaryEntry objects, and each time through get the Value property. If we wanted to get the key, it would be a simple matter of replacing the Value property call with a call to Key.

If you are in a situation where you are not sure of the data types being used in the keys or the values, you should append a .ToString() after a reference to the Key or Value so as not to generate run time errors when displaying. In the above example, we’d have needed to use Console.WriteLine(myEntry.Key.ToString()); since our keys were integers (1, 2, and 3).

As you can see, the hashtable makes it easy to look up values when you have a specific key, yet at the same time is still flexible enough to allow you to iterate over your entire collection when you need to.

About these ads

12 Responses to “Dictionaries in C#: The Hashtable”

  1. Joanna Watts Says:

    Hi, your homepage looks really good and gives great information! Anyway, nice job. Keep it up please!!! My best wishes to you all!

  2. David Says:

    What are the size limits both in terms of key-length and in terms of # entries before it bogs down on add/retrieve?

  3. arcanecode Says:

    From what I have been able to determine David, the best answer I can find is “it depends”.

    I know, it seems like it’s always the answer, but in part it’s tied to your machine’s hardware. Amount of RAM, CPU speed, single vs. dual core, etc.

    The best advice I can give is to do some trial tests at what you expect the upper bounds of your hashtable to be with realistic data in it, and see what happens.

    Arcane

  4. zar Says:

    hi,
    I need dictionary code , with c# and sql server 2000.
    please help me.

  5. Arif Says:

    I want to fetch the Hashtable items in the same sequence in which I added in it using foreach loop with the help of DictionaryEntry. How it can be done.

  6. gayathri Says:

    Hi, i have a problem. The data that i get using the hastable is gettin lost when i try to bind it to the combo box. Plss help me solve the issue.

  7. Feitz Says:

    Thanks for the help tips in your website. just the information i need! =)

  8. Andy Says:

    usign System.Collections;

  9. vanit Says:

    Hello
    When i am using the Hashtable them i am getting this error.

    Error Description: Item has already been added. Key in dictionary: ‘ProjectList’ Key being added: ‘ProjectList’

    can you please tell me where i am wrong ?

    Thanks
    Vanit

    • Michael Blackburn Says:

      Vanit, a hashtable requires that each key be unique. Once you add a key to a hashtable, you cannot add it again. You CAN update the value, as you see in his first code example, he changes the value at the key ArcaneCode to “Here I’ve changed the value.”
      You can do this:
      hash.Add(“myKey”,1);
      hash["myKey"] = 2;

      But you can’t do this:
      hash.Add(“myKey”,1);
      hash.Add(“myKey”,2);


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 )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 106 other followers

%d bloggers like this: