C#:Dictionary

.NET Array Dictionary List String 2D Async DataTable Dates DateTime Enum File For Foreach Format IEnumerable If IndexOf Lambda Parse Path Process Property Regex Replace Row Sort Split Static StringBuilder Substring Switch Tuple Window

Hashtable. This optimizes lookups. It computes a hash of each key you add. It then uses this hash code to look up the element very quickly.
Don't use this. It is an older .NET Framework type. It is slower than the generic Dictionary type. But if an old program uses Hashtable, it is helpful to know how to use this type.Dictionary
First example. We create a Hashtable with a constructor. When it is created, the Hashtable has no values. We directly assign values with the indexer, which uses the square brackets.

Next: The example adds three integer keys, with one string value each, to the Hashtable object.

Result: The program displays all the DictionaryEntry objects returned from the enumerator in the foreach-loop.

WriteLine: The WriteLine call contains a format string that displays the key-value pairs with a comma.

Based on: .NET 4.5

C# program that adds entries to Hashtable

using System;
using System.Collections;

class Program
{
    static void Main()
    {
	Hashtable hashtable = new Hashtable();
	hashtable[1] = "One";
	hashtable[2] = "Two";
	hashtable[13] = "Thirteen";

	foreach (DictionaryEntry entry in hashtable)
	{
	    Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
	}
    }
}

Output

13, Thirteen
2, Two
1, One
Foreach. You can loop through the Hashtables by using the DictionaryEntry type in a foreach-loop. You can alternatively get the Keys collection and copy it into an ArrayList.Foreach
DictionaryEntry. A DictionaryEntry contains two objects: the key and the value. This is similar to a KeyValuePair from the newer generic Dictionary.DictionaryEntryKeyValuePair
ContainsKey. You will want to call ContainsKey on your Hashtable with the key contents. This method returns true if the key is found, regardless of the value.

Also: Contains works the same way. We see an example of using the indexer with the square brackets.

C# program that uses Contains method

using System;
using System.Collections;

class Program
{
    static Hashtable GetHashtable()
    {
	// Create and return new Hashtable.
	Hashtable hashtable = new Hashtable();
	hashtable.Add("Area", 1000);
	hashtable.Add("Perimeter", 55);
	hashtable.Add("Mortgage", 540);
	return hashtable;
    }

    static void Main()
    {
	Hashtable hashtable = GetHashtable();

	// See if the Hashtable contains this key.
	Console.WriteLine(hashtable.ContainsKey("Perimeter"));

	// Test the Contains method. It works the same way.
	Console.WriteLine(hashtable.Contains("Area"));

	// Get value of Area with indexer.
	int value = (int)hashtable["Area"];

	// Write the value of Area.
	Console.WriteLine(value);
    }
}

Output

True
True
1000
Objects. An indexer is a property that receives an argument inside square brackets. The Hashtable implements indexers. It returns plain objects so you must cast them.Indexer
Multiple types. The example here adds string keys and int keys. Each of the key-value pairs has different types. You can put them all in the same Hashtable.

Warning: This code might throw exceptions. Casting is a delicate operation. It is hard to get right.

Info: If the cast was applied to a different type, the statement could throw an InvalidCastException. We avoid this with "is" or "as."

C# program that uses multiple types

using System;
using System.Collections;

class Program
{
    static Hashtable GetHashtable()
    {
	Hashtable hashtable = new Hashtable();

	hashtable.Add(300, "Carrot");
	hashtable.Add("Area", 1000);
	return hashtable;
    }

    static void Main()
    {
	Hashtable hashtable = GetHashtable();

	string value1 = (string)hashtable[300];
	Console.WriteLine(value1);

	int value2 = (int)hashtable["Area"];
	Console.WriteLine(value2);
    }
}

Output

Carrot
1000
Cast. You can use the as-operator to attempt to cast an object to a specific reference type. If the cast does not succeed, the result will be null.Null

Is: You can also use the is-operator. This operator returns true or false based on the result.

Is

As: With Hashtable, you can reduce the number of casts by using the as-operator. This is a performance warning given by FxCop.

AsFxCop
C# program that casts Hashtable values

using System;
using System.Collections;
using System.IO;

class Program
{
    static void Main()
    {
	Hashtable hashtable = new Hashtable();
	hashtable.Add(400, "Blazer");

	// This cast will succeed.
	string value = hashtable[400] as string;
	if (value != null)
	{
	    Console.WriteLine(value);
	}

	// This cast won't succeed, but won't throw.
	StreamReader reader = hashtable[400] as StreamReader;
	if (reader != null)
	{
	    Console.WriteLine("Unexpected");
	}

	// You can get the object and test it.
	object value2 = hashtable[400];
	if (value2 is string)
	{
	    Console.Write("is string: ");
	    Console.WriteLine(value2);
	}
    }
}

Output

Blazer
is string: Blazer
Keys, values. We can loop over keys and values, or store them in an ArrayList. This example shows all the keys, then all the values, and then stores the keys in an ArrayList.

Note: This Hashtable example uses the Keys property. This property returns all the keys.

Keys: The first loop in the program loops over the collection returned by the Keys instance property on the Hashtable instance.Values: The second loop in the program shows how to enumerate only the values in the Hashtable instance.

Console.WriteLine

Copy: We create a new ArrayList with the copy constructor and pass it the Keys (or Values) property as the argument.

ArrayList
C# program that loops over Keys, Values

using System;
using System.Collections;

class Program
{
    static void Main()
    {
	Hashtable hashtable = new Hashtable();
	hashtable.Add(400, "Blaze");
	hashtable.Add(500, "Fiery");
	hashtable.Add(600, "Fire");
	hashtable.Add(800, "Immolate");

	// Display the keys.
	foreach (int key in hashtable.Keys)
	{
	    Console.WriteLine(key);
	}

	// Display the values.
	foreach (string value in hashtable.Values)
	{
	    Console.WriteLine(value);
	}

	// Put keys in an ArrayList.
	ArrayList arrayList = new ArrayList(hashtable.Keys);
	foreach (int key in arrayList)
	{
	    Console.WriteLine(key);
	}
    }
}

Output

800       (First loop)
600
500
400
Immolate  (Second loop)
Fire
Fiery
Blaze
800       (Third loop)
600
500
400
Keys and values, notes. The Keys and Values public accessors return a collection of the keys and values in the Hashtable at the time they are accessed.

However: If you need to look at all the keys and values in pairs, it is best to enumerate the Hashtable instance itself.


Count, Clear. You can count the elements in a Hashtable with the Count property. The example also shows using the Clear method to erase all the Hashtable contents.

Tip: An alternative to Clear() is to reassign your Hashtable reference to a new Hashtable().

Note: This example shows how to use the Count property. This property returns the number of elements.

First: We add data to the Hashtable. It captures the Count, which is 4. It then uses Clear on the Hashtable, which now has 0 elements.

C# program that uses Count

using System;
using System.Collections;

class Program
{
    static void Main()
    {
	// Add four elements to Hashtable.
	Hashtable hashtable = new Hashtable();
	hashtable.Add(1, "Sandy");
	hashtable.Add(2, "Bruce");
	hashtable.Add(3, "Fourth");
	hashtable.Add(10, "July");

	// Get Count of Hashtable.
	int count = hashtable.Count;
	Console.WriteLine(count);

	// Clear the Hashtable.
	hashtable.Clear();

	// Get Count of Hashtable again.
	Console.WriteLine(hashtable.Count);
    }
}

Output

4
0
Count property, notes. Count returns the number of elements in the Hashtable. This property does not perform lengthy computations or loops.

Note: MSDN states that, for Count, "retrieving the value of this property is an O(1) operation."

Time: This property is a constant-time accessor. It returns an integer and is a simple accessor with low resource demands.


Benchmark. We test the Hashtable collection against the Dictionary. The benchmark first populates an equivalent version of each collection.

Then: It tests one key that is found and one that is not found. It repeats this 20 million times.

Hashtable used in benchmark: C#

Hashtable hashtable = new Hashtable();
for (int i = 0; i < 10000; i++)
{
    hashtable[i.ToString("00000")] = i;
}

Dictionary used in benchmark: C#

var dictionary = new Dictionary<string, int>();
for (int i = 0; i < 10000; i++)
{
    dictionary.Add(i.ToString("00000"), i);
}

Statements benchmarked: C#

hashtable.ContainsKey("09999")
hashtable.ContainsKey("30000")

dictionary.ContainsKey("09999")
dictionary.ContainsKey("30000")

Benchmark of 20 million lookups

Hashtable result:  966 ms
Dictionary result: 673 ms
Results, benchmark. Hashtable is slower than the Dictionary code. I calculate that Hashtable here is 30% slower. This means that for strongly-typed collections, the Dictionary is faster.
Constructors. The 15 overloaded constructors provide ways to specify capacities. They let you copy existing collections. You can also specify how the hash code is computed.Constructor
A summary. Hashtable is an older collection that is obsoleted by the Dictionary collection. Knowing how to use it is critical when maintaining older programs. These programs are important.