Dictionary Implementation of Hashtable in .NET Framework
Hashtable myHashedEemail = new Hashtable();
myHashedEemail.Add("test@test.com", "Joe, Doe");
myHashedEemail ["email@site.com"] = "James, Shmo";
Indexer also helps with the retrieval of the value
Console.WriteLine(myHashedEemail ["test@test.com "]); Hashtable stores objects so iteration is not as simple as with lists. Here is how it’s done. First we iterate via object by casting them at the same time since we know they are DictioanryEntry objects and then getting property of these objects.
foreach (DictionaryEntry myEntry in myHashedEemail)
{
Console.WriteLine(myEntry.Value);
}
Or
foreach (object myName in myHashedEemail.Values)
{
Console.WriteLine(myName);
}
Dictionary classes support IDictionary interface which is derived from ICollection interface and Hastable also supports IDictionary.
Properties of IDictionary
Name | Description |
---|---|
IsFixedSize | Deterines an indicator of whether this collection can be resized |
IsReadOnly | Deterines an indicator of whether a collection can be changed |
Item | Deterines or sets the item at a specific element in the collection |
Keys | Deterines an ICollection object containing a list of the keys |
Values | Deterines an ICollection object containing a list of the values in the collection |
Methods
Name | Description |
---|---|
Add | Adds a key/value |
Clear | Removes all items |
Contains | Key is contained |
GetEnumerator | Returns an IDictionaryEnumerator object |
Remove | Removes the item in the collection |
IDictionary does not have index like IList and allow access only by key.
In addition to IDictionary method Hashtable has additional two methods
Name | Description |
---|---|
ContainsKey | collection contains a specific key |
ContainsValue | collection contains a specific value |
When we store value in the Hashtable it creates unique value that identifies this value since it’s derive from Object class it has this method GetHash and uses GetHashCode to get this unique value from the object. However, we can reference value with the string and in this case it will return only one value even when we replace value with another value for the same key. However, by creating and saving Object we used Object GetHashValue which is unique so we get two results.
Hashtable myHashOne = new Hashtable();
myHashOne["First"] = "1st";
myHashOne["First"] = "the first";
Console.WriteLine(myHashOne.Count); // 1
Vs.
Hashtable myHashOne = new Hashtable();
Fish key1 = new Fish("Herring");
Fish key2 = new Fish("Herring");
myHashOne[key1] = "Hello";
myHashOne[key2] = "Hello";
Console.WriteLine(myHashOne.Count); // 2
To compare two objects we need to compare names.