Welcome to this tutorial on Using The Hashtable Collection in C#. Hashing eliminates the resources normally needed for searching and retrieving data, since it uses the value of the key to find the requested data. We will be using the
Hashtable Class, located in the
System.Collections Namespace, thus eliminating the need to write our own Hashtable.
A Hashtable uses a (Key, Value) pair when storing the data, and uses the
Key to find the requested data item. The
Key value is
immutable , and cant be duplicated in a Hashtable Class. In this tutorial we will create a
Song Class, this class will be stored in a Hashtable, and we will use the name of the song for the key.
Creating The ClassFor our
Song Class, since it is going to be a simple class with but 2 Propeties, the only Namespace we need to Import is the
System Namespace, this is the base of all other Namespaces, to import it do:
csharp
In this class we will have 2
Properties, one for the path to the song, one for the name of the song. As with all properties, we will need 2 private variables which will hold the values of our Properties for us. The variables are private as we don't want the user to be able to change their value directly.
Our 2 properties are Read/Write Properties, meaning they have a
get and a
set. The
Get is used to retrieve the value of the property while the
Set is used to set the value of the property:
csharp
#region Property Variables
/// <summary>
/// path property variable
/// </summary>
private string _path;
/// <summary>
/// name property variable
/// </summary>
private string _name;
#endregion
#region Class Properties
/// <summary>
/// property to hold the path to the song
/// </summary>
public string Path
{
get { return _path; }
set { _path = value; }
}
/// <summary>
/// property to hold the name of the song
/// </summary>
public string Name
{
get { return _name; }
set { _name = value; }
}
#endregion
NOTE: You will notice my code is seperated into sections with the
#region...#endregion specifier. This allows me to divide similar sections of code, making it easier when searching through my code.
Next we will use a
Constructor. In C# when you create a class as we are it is assumed by the Framework that a default Constructor is present, in fact if you do not add one, the default empty Constructor is assumed if you will. We are going to add a Constructor though, we will be setting the values of our property variables in our constructor, like so:
csharp
#region Constructor
/// <summary>
/// class constructor to set the values of our class properties
/// </summary>
/// <param name="path">path to the song</param>
/// <param name="name">name of the song</param>
public Song(string path, string name)
{
//set the value of the path property
_path = path;
//set the value of the name property
_name = name;
}
#endregion
We have one more method in our sample class. With this method we are going to override the default
ToString Method. Doing this will allow us to return the full value of the song, path and name, when we get to retrieving the values of our class. In .Net we are allowed to override base methods, as long as we use the
override Modifier. Our new
ToString method looks like this:
csharp
#region ToString
/// <summary>
/// here we will override the ToString method in the .Net
/// Framework so when this class is used and called, ToString()
/// will return the path & name of the song
/// </summary>
/// <returns></returns>
public override string ToString()
{
return _path + "\\" + _name;
}
#endregion
Now that we have our
Song Class complete, we will next look at how we can use it, along with the
Hashtable Class, to make storing and retrieving data easier and more efficient.
Using The ClassFirst thing we will be doing is creating an instance of our
Song Class, and a
Hashtable Object for holding our
Song objects. In this tutorial I am referencing a TreeView which I have populated with my music library, but you do not have to use it in this manner, this is just for demonstration purposes. What I did was I created a global variable which is an instance of the Hashtable Class, and an instance of our
Song Class:
csharp
//Hashtable object to hold our Song objects
Hashtable songs = new Hashtable();
//Create an instance of our Song class
Song song;
I then loop through each checked item in my TreeView Control, and if it has been checked, I create a new
Song Object, then add it to my Hashtable, like so:
csharp
/// <summary>
/// method for adding all checked items in the TreeView to
/// my Hashtable Object
/// </summary>
private void AddSongs()
{
//extensions we want to load
string[] extensions = { ".mp3", ".wma", ".mp4", ".wav" };
//now we will loop through all the checked
//items in our TreeView
foreach(TreeNode items in tvCurrentLists.Nodes)
{
//make sure the node's CheckBox is checked
if (items.Checked == true)
{
//now we will make sure what we're adding is actually a song
//to do this we will loop through our extensions list
for (int i = 0; i < extensions.Length; i++)
{
//now check the value of the current node
if (items.FullPath.Contains(extensions[i]))
{
//since it's a song we can now add it to our
//Hashtable, only after we create a Song
//Object out of it
song = new Song("YourPath", items.FullPath);
//now add it to our Hashtable
songs.Add(song.Name, song);
}
}
}
}
}
Since we now have our
Song Object populated, displaying the values is simply. We will loop through each
Song in our Hashtable object, pass in our
Key to the
indexer, which is the name of the song, then display each song name in a MessageBox, like so:
csharp
private void cmdDisplay_Click(object sender, EventArgs e)
{
//now we will use the Hashtable indexer to display the
//values of our Hashtable Object
foreach(Song item in songs)
{
//display the value of each song
MessageBox.Show(songs[item.Name].ToString());
}
}
Another way we can achieve the same results would be to use the
IDictionaryEnumerator Interface to enumerate through each item in our Hashtable object. To do this we will create an instance of the IDictionaryEnumerator Interface, then use the
GetEnumerator Method of the Hashtable Class.
To enumerate through the objects in our Hashtable, and to ensure we don't cause any Exceptions by attempting to go past the end of our list, we'll use the
MoveNext Method, which equates to true or false depending on the position of the enumerator, like this:
csharp
private void cmdDisplay_Click(object sender, EventArgs e)
{
//variable to hold the list of songs
string list = string.Empty;
//create an instance of the IDictionaryEnumerator Interface
IDictionaryEnumerator enumerator;
//make sure our Hashtable holds items
if (songs.Count > 0)
{
//let the user know what we're doing
MessageBox.Show("The following songs are in your list:");
//now set out IDictionaryEnumerator value
enumerator = songs.GetEnumerator();
//now use the MoveNext Method to iterate through our list
while (enumerator.MoveNext())
{
//keep adding song names until we reach the end
list += enumerator.Value.ToString() + "\r\n";
}
//now show the song names
MessageBox.Show(list);
}
}
That is how you can effectively use the Hashtable Collection in C#. This tutorial isn't meant to be an all inclusive tutorial, there are many more methods available to you in the Hashtable Class, but I am hoping this will give you enough information to get started using the Hashtable Class, and the IDictionary and IDictionaryEnumerator Interfaces.
As you can see the Hashtable is an efficient way ot storing and retrieving data in your applications, and uses less overhead than other methods because it uses the
(Key, Value) pairs to store the data, thus only requiring the
Key to retrieve it's value. Using this method doesn't require traditional search methods.
I hope you found this tutorial informative and useful, and thank you for reading

Happy Coding!