Professor Mustard Programming
 

Programming 101 - Unit 06 - Other Features

06d) Hashtables
 
I'm going to be brief (for a change), and simply introduce you Hashtables before turning you over to the code sample.

All the collections you've seen so far use an integer-based key to index their values. In addition, the indexes were linear: 0, 1, 2, 3, and so on. A Hashtable is a special kind of collection that allows you to use any possible datatype as your index (we tend to call them "keys" when dealing with Hashtables). Although any datatype can be used as a Hashtable key, strings are the most common, since they can be used to associate a specific descriptive key with a given value.

As with enums, a large benefit with Hashtables is the ability to represent values in a format that is more meaningful than arbitrary, incrementing numbers. Why attach significance to an arbitrary array index, when you can store a value under the actual name of the thing it represents?

Outside of this special ability, hashtables are used in much the same way as ArrayLists. They can be added to and removed from dynamically, and possess both a Count property and Clear() method. ArrayLists (and other collections like it) are more useful for general-purpose storage of multiple values, but there are definitely some situations where you'll want to use a Hashtable, instead. Whenever you want to associate a significant value with each element in a collection (instead of an arbitrary numeric index), consider using a Hashtable.

As a "real-world" example, I programmed a game that had a collection of sound effects. I didn't want to remember that the "Jump" sound effect was stored at index 4, and the "Shoot" sound effect was stored at index 9, or whatever. Instead, I stored them in a Hashtable, and I used the sound effect's name as the key. So, when I wanted to retrieve the "Jump" sound effect, I simply pulled the sound effect that was stored under the "Jump" key. What's easier to remember as the index of the "Jump" sound effect? "Jump" or 4? Besides making my code easier to write, it also made my code easier to read. After all, you could look at any key name I was accessing, and know exactly what kind of sound effect was being used.

Anyways, that's all on Hashtables for now. I've finished early today, as promised! Review the code sample, and let's move on.



using System;
using System.Collections; // Required reference to use Hashtable

namespace D_Hashtables
{
  class Class1
  {
    static readonly string ln = Environment.NewLine;

    [STAThread]
    static void Main(string[] args)
    {
      // Declare a hashtable
      Hashtable hash = new Hashtable();

      // As with an ArrayList, we can store
      // anything in a Hashtable. However,
      // we can also use anything for an index!
      // In a hashtable, indexes are called "keys".

      // Store some variables, using strings as keys.
      hash.Add("This is a key.", 5);
      hash.Add("Any string will do.", 8.4);
      hash.Add("Penguin", true);

      // Access a value from the hashtable.
      // This will access the 8.4 that we stored earlier.
      Console.WriteLine(hash["Any string will do."].ToString());

      // Don't forget that we need to cast when referencing variables
      // out of the hashtables. The same rules with ArrayLists apply here.
      int number = (int)hash["This is a key."];

      // Check to see if a key exists in the hashtable.
      if( hash.ContainsKey("This is a key") )
        Console.WriteLine("That's one of the keys in the hashtable!");

      // Check to see if a value exists in the hashtable.
      if( hash.ContainsValue(true) )
        Console.WriteLine("That value is stored in at least one of the hashtable's keys!");

      // --> Print all hashtable keys, and their corresponding values. <--

      // Step 1: Create a string[] big enough to hold all the keys.
      // Obviously, the array needs to be the same datatype that we used for the keys.
      string[] keys = new string[hash.Keys.Count];

      // Step 2: Copy the hashtable's keys into our string[]
      hash.Keys.CopyTo(keys, 0);

      // Step 3: Fetch the value at each key, and display it.
      foreach(string key in keys)
      {
        object obj = hash[key];
        Console.WriteLine(ln + "DATA STORED IN KEY " + key + ":");
        Console.WriteLine(" DataType: " + obj.GetType().Name);
        Console.WriteLine(" Value: " + obj.ToString());
      }

      // Note that we can also get all of the hashtable's values directly,
      // by using hash.Values.

      // Remove a specific key (and its value) from the hashtable
      hash.Remove("Penguin");

      // Clear the entire hashtable (blow away all keys and values)
      hash.Clear();

      PromptForExit();
    }

    static void PromptForExit()
    {
      Console.Write(ln + "Program complete! Hit enter to exit...");
      Console.ReadLine();
    }
  }
}