BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 1.1+

The Hashtable Collection

The thirty-eighth part of the C# Fundamentals tutorial describes the use of the Hashtable class. This provides general-purpose dictionary collections allowing the items in a collection to be addressed not by an index number, but by an object-based key.

ContainsKey

As described in a previous article within the C# Fundamentals tutorial, all collections that implement IDictionary include a method named Contains that returns a Boolean value indicating if a specified key exists within the collection. The Hashtable includes this method and another named ContainsKey that provides exactly the same functionality.

ContainsValue

In addition to determining if a specific key exists within a Hashtable, it can be useful to check if a value occurs within the collection. The ContainsValue operates in a similar manner to Contains and ContainsKey; the object to test for is passed as the only parameter. The resultant Boolean is true if the object exists and false otherwise.

Hashtable fruit = new Hashtable();
fruit.Add("apple","Granny Smith");
fruit.Add("banana","Cavendish");
fruit.Add("cherry","Yamagata");
fruit.Add("orange","Seville");

Console.WriteLine(fruit.ContainsValue("Seville"));      // Outputs "True"
Console.WriteLine(fruit.ContainsValue("Valencia"));     // Outputs "False"

Creating a Thread-Safe Hashtable Wrapper

In the earlier article discussing collection interfaces, the concept of a thread-safe synchronised collection was described. In order to create a thread-safe Hashtable, a synchronised wrapper dictionary is generated using the static Synchronized method.

Hashtable myDictionary = new Hashtable();
Hashtable myThreadSafe = Hashtable.Synchronized(myDictionary);
Console.WriteLine(myThreadSafe.IsSynchronized);	        // Outputs "True"
20 May 2007