Microsoft KB Archive/309357

= How to work with the HashTable collection in Visual C# =

Article ID: 309357

Article Last Modified on 12/11/2006

-

APPLIES TO


 * Microsoft Visual C# 2005
 * Microsoft Visual C# .NET 2002 Standard Edition
 * Microsoft Visual C++ .NET 2003 Standard Edition

-



This article was previously published under Q309357



For a Microsoft Visual Basic .NET version of this article, see 307933.

IN THIS TASK
SUMMARY
 * Steps to Build the Sample



SUMMARY
This step-by-step article shows you how to use the HashTable collection. Because hashing eliminates the need for costly searching of data to retrieve the data, you can use hashing to efficiently retrieve data. Hashing uses the value of the key itself to locate of the data.

The Base Class Libraries offer a HashTable class that is defined in the System.Collections namespace so that you are not required to code your own hash tables.

back to the top

Steps to Build the Sample
A HashTable collection stores a (Key, Value) pair and uses the Key to hash and obtain the storage location. The Key is immutable and cannot have duplicate entries in the HashTable. This sample uses several instances of a simple Person class to store in a HashTable. The last name is used as the Key.  Open Microsoft Visual Studio .NET, and create a Windows Application project in Visual C# .NET. Form1 is added to the project by default.

Note The code should be changed in Visual Studio 2005. For more information, visit the following Microsoft Developer Network (MSDN) Web site:

http://msdn2.microsoft.com/en-us/library/ms173077.aspx

When you create a Windows Forms project, Visual C# adds one form to the project by default. This form is named Form1. The two files that represent the form are named Form1.cs and Form1.designer.cs. You write your code in Form1.cs. The designer.cs file is where the Windows Forms Designer writes the code that implements all the actions that you performed by dragging and dropping controls from the Toolbox. In Solution Explorer, right-click the project name, point to Add, and then click Add Class to add a Class module. Class1 is added to the project by default.  Replace any code in the Class1 module with the following code: public class Person {   public string Fname, Lname;

public Person(string FirstName, string LastName) {       Fname = FirstName; Lname = LastName; }

public override string ToString {       return Fname + &quot; &quot; + Lname; } } The Person class has one constructor that takes the FirstName and LastName parameters and assigns these parameters to the local variables. The ToString function overrides ToString from the Object class to return Fname and Lname concatenated together.   Create a form-level Hashtable object, and declare three variables of type Person. Add the following code to the Form1 class: private Hashtable MyTable = new Hashtable; //For simplicity, create three Person objects to add to the HashTable collection.

Person Person1,Person2,Person3;  In the following steps, use the Add method of the Hashtable object to add three Person objects to the Hashtable in a try-catch block. The try-catch block catches the exception and displays a message if duplicate keys exist.  Place a Button control on Form1, and change the Text property to Add Items .  Double-click the button to open its Code window, and paste the following code in the Button1_Click event: Person1 = new Person(&quot;David&quot;, &quot;Burris&quot;); Person2 = new Person(&quot;Johnny&quot;, &quot;Carrol&quot;); Person3 = new Person(&quot;Ji&quot;, &quot;Jihuang&quot;);

//The Add method takes Key as the first parameter and Value as the second parameter.

try {       MyTable.Add(Person1.Lname, Person1); MyTable.Add(Person2.Lname, Person2); MyTable.Add(Person3.Lname, Person3); } catch (ArgumentException ae) {   MessageBox.Show(&quot;Duplicate Key&quot;); MessageBox.Show(ae.Message); }                       </li></ol> </li> The Hashtable object provides an indexer. In the following steps, index with the Key to access the value that is stored at the hashed location. <ol style="list-style-type: lower-alpha;"> Add a Button control to Form1, and change the Name property to Get Items .</li>  Double-click the button, and paste the following code in the Button2_Click event: //Use the indexer of the Hashtable class to retrieve your objects. The indexer takes //Key as a parameter and accesses it with the Hashed location.

try {       MessageBox.Show(MyTable[Person1.Lname].ToString); MessageBox.Show(MyTable[Person2.Lname].ToString); MessageBox.Show(MyTable[Person3.Lname].ToString); } catch (NullReferenceException ex) {   MessageBox.Show(&quot;Key not in Hashtable&quot;); MessageBox.Show(ex.Message); }                        </li></ol> </li> In the following steps, use the Remove method to remove a single item from the HashTable collection: <ol style="list-style-type: lower-alpha;"> Add a Button control to Form1, and change the Text property to Remove Item .</li>  Double-click the button, and paste the following code in the Button3_Click event: if (MyTable.Count == 0) {   MessageBox.Show(&quot;There are no items in HashTable&quot;); } else {       MessageBox.Show(&quot;The count before removing an Item is&quot; + &quot; &quot; + MyTable.Count); MessageBox.Show(&quot;Removing value stored at key value (Burris)&quot;); Remove the object that is stored at the Key value Person1.Lname. MyTable.Remove(Person1.Lname); }                       </li></ol> </li> In the following steps, enumerate the items that are stored in the HashTable collection. <ol style="list-style-type: lower-alpha;"> Add a Button control to Form1, and change the Text property to Enumerate .</li>  Double-click the button, and paste the following code in the Button4_Click event: IDictionaryEnumerator Enumerator;

if (MyTable.Count == 0) MessageBox.Show(&quot;The hashtable is empty&quot;); else {   MessageBox.Show(&quot;Enumerating through the Hashtable collection&quot;); Enumerator = MyTable.GetEnumerator; while (Enumerator.MoveNext) {           MessageBox.Show(Enumerator.Value.ToString); } }

ICollection MyKeys;

if (MyTable.Count == 0) MessageBox.Show(&quot;The hashtable is empty&quot;); else {      MessageBox.Show(&quot;Accessing keys property to return keys collection&quot;); MyKeys = MyTable.Keys;

foreach (object Key in MyKeys) {       MessageBox.Show(Key.ToString); }                                  }  This code declares a variable of type IDictionaryEnumerator and calls the GetEnumerator method of the HashTable collection. With the Enumerator returned, the code enumerates through the items in the collection and uses the Keys method of the HashTable to enumerate through the keys. </li></ol> </li> In the following steps, use the Clear method to clear the HashTable. <ol style="list-style-type: lower-alpha;"> Add a Button control to Form1, and change the Text property to Clear .</li>  Double-click the button, and paste the following code in the Button5_Click event: MyTable.Clear; MessageBox.Show(&quot;HashTable is now empty&quot;); </li></ol> </li> Follow these steps to build and run the application: <ol style="list-style-type: lower-alpha;"> Click Add Items. Note that three Person objects are added to the HashTable collection.</li> Click Get Items. Note that the indexer obtains the items in the HashTable collection. The three newly added items are displayed.</li> <li>Click Remove Item. Note that the item at the &quot;Burris&quot; key location is deleted.</li> <li>Click Enumerate. Note that IDictionaryEnumerator enumerates through the items in the HashTable collection, and the Keys property of the HashTable returns a Keys Collection.</li> <li>Click Clear. Note that all the items are cleared from the HashTable collection.</li></ol> </li></ol>

NOTE: The example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious. No association with any real company, organization, product, domain name, email address, logo, person, places, or events is intended or should be inferred.

back to the top

Keywords: kbhowtomaster KB309357

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.