Introduction
A group of key/value pairs arranged according to the key's hash code is represented by the Hashtable class. This class is contained in the namespace System. Collections. To execute different kinds of operations on the hashtables, the Hashtable class offers a variety of methods. To access the elements that are part of the collection in a hashtable, keys are required. On a 64-bit machine, you can raise the maximum capacity for very big hashtable objects to 2 billion items.
Features of Hashtables in C#
- The elements are kept in C# as key-value pairs by the Hashtable Collection Class.
- The class Hashtable is a part of the System. Collections namespace, It is a Non-Generic Collection class.
- The IDictionary interface is implemented by it.
- Any type of data may be used for the keys, but they must be distinct and not null.
- Null and duplicate values are both accepted by the hashtable.
- By utilizing the related key, we are able to retrieve the values.
- The maximum number of elements that a hashtable may contain is known as its capacity.
- Since a hashtable is a non-generic collection, both distinct and identical elements can be stored in it.
What makes an ArrayList different from a Hashtable in C#?
- Performance: Because hashtables do additional duties, such as hashing, array lists are faster than hashtables.
- Lookup: The index number that is created internally is the only way to look up an ArrayList. A custom-defined key can be used to look up hashtable entries.
- Scenario: Use a hashtable to obtain a key lookup. Use ArrayList if all you want to do is add a browser via a collection.
How can I use C# to make a Non-Generic Hashtable Collection?
As seen in the figure below, the C# Non-Generic Hashtable class has sixteen distinct constructor types that we can use to create a hashtable. Any of the overloaded constructors can be used to build a Hashtable instance.
![Hashtable instance]()
Here, we're going to use the overloaded version—that is, the following Hashtable constructor—which doesn't require any parameters.
public Hashtable()
This function initializes a new, empty instance of the Hashtable class with the load factor, comparer, hash code provider, and starting capacity set to default.
Creating the Hashtable
Hashtable hashtable = new Hashtable();
Add Elements in the Hashtable
The hash table provides the Add method, so we can use that method for adding the data to the hash table.
hashtable.Add("Id", 1);
hashtable.Add("Name", "Jaimin Shethiya");
![Hashtable]()
Modify data in the hashtable
hashtable provides the modified data that has been inserted in the hashtable.
hashtable["Id"] = 134;
hashtable["Name"] = "C# Corner";
![Modify data]()
Check existing data in the hashtable
The hash table provides a way to check if any key exists in the hashtable or not, or if you want to check the hashtable value, it also provides it to us.
Hashtable hashtable = new Hashtable();
hashtable.Add("Id", 1);
hashtable.Add("Name", "Jaimin Shethiya");
Console.WriteLine("Exists Id: {0}", hashtable.Contains("Id"));
Console.WriteLine("Exists Type: {0}", hashtable.Contains("Type"));
Console.WriteLine("Exists Id: {0}",hashtable.ContainsKey("Id"));
Console.WriteLine("Exists Type: {0}", hashtable.ContainsKey("Type"));
Console.WriteLine("Exists Value: {0}", hashtable.ContainsValue("Jaimin Shethiya"));
Console.WriteLine("Exists Value: {0}", hashtable.ContainsValue("C# Corner"));
![Hashtable value]()
Remove elements from the hashtable
If you want to remove any elements from the hashtable, that is also possible; for that, we need to use the Remove() method.
Hashtable hashtable = new Hashtable();
hashtable.Add("Id", 1);
hashtable.Add("Name", "Jaimin Shethiya");
hashtable.Add("Location", "Vadodara");
Console.WriteLine("Total elements inside the hashtable: {0}",hashtable.Count);
hashtable.Remove("Id");
Console.WriteLine("After removing Id, Total elements inside the hashtable: {0}", hashtable.Count);
if (hashtable.ContainsKey("Salary"))
{
hashtable.Remove("Salary");
}
![Remove elements]()
Clear elements from the hashtable
If you want to remove all of the data from the hashtable, we need to use the Clear() method.
Hashtable hashtable = new Hashtable();
hashtable.Add("Id", 1);
hashtable.Add("Name", "Jaimin Shethiya");
hashtable.Add("Location", "Vadodara");
Console.WriteLine("Total elements inside the hashtable: {0}",hashtable.Count);
hashtable.Clear();
Console.WriteLine("After clearing Total elements inside the hashtable: {0}", hashtable.Count);
![Clear elements]()
Clone elements from the hashtable
If you want to clone the hashtable data, then that is also possible here; we want to use the Clone() method.
Hashtable hashtable = new Hashtable();
hashtable.Add("Id", 1);
hashtable.Add("Name", "Jaimin Shethiya");
hashtable.Add("Location", "Vadodara");
foreach (DictionaryEntry item in hashtable)
{
Console.WriteLine("{0} - {1}", item.Key, item.Value);
}
Hashtable cloneHashtable = (Hashtable)hashtable.Clone();
Console.WriteLine();
Console.WriteLine("Clone hash table elements:");
foreach (DictionaryEntry item in hashtable)
{
Console.WriteLine("{0} - {1}", item.Key, item.Value);
}
![Clone elements]()
Copy hashtable elements to an existing array
If you want to copy the hashtable elements to the existing one-dimensional array, that is also possible here; we need to use the CopyTo() method.
Hashtable hashtable = new Hashtable();
hashtable.Add("Id", 1);
hashtable.Add("Name", "Jaimin Shethiya");
hashtable.Add("Location", "Vadodara");
foreach (DictionaryEntry item in hashtable)
{
Console.WriteLine("{0} - {1}", item.Key, item.Value);
}
var keys = new object[hashtable.Count];
hashtable.Keys.CopyTo(keys, 0);
Console.WriteLine("\nCopy keys:");
foreach (var key in keys)
{
Console.WriteLine(key);
}
var values = new object[hashtable.Count];
hashtable.Values.CopyTo(values, 0);
Console.WriteLine("\nCopy values:");
foreach (var value in values)
{
Console.WriteLine(value);
}
var copyHasttable = new object[hashtable.Count];
hashtable.CopyTo(copyHasttable, 0);
Console.WriteLine("\nCopy hashtable:");
foreach (DictionaryEntry item in copyHasttable)
{
Console.WriteLine("{0} - {1}", item.Key, item.Value);
}
![Copy hashtable]()
Advantages of the hashtable
- Dynamic Size: As the amount of elements varies, hash tables have the ability to dynamically resize themselves.
- Key Flexibility: Hash tables provide a variety of key types. Hash tables allow for the use of a variety of data types as keys, including strings, in contrast to arrays, where the keys are usually numbers that represent indices.
- Effective Search, Insertion, and Deletion: In general, a hash table's items may be found, added to, and removed quickly. A hash table's average time complexity for searches, insertions, and deletions is likewise O(1).
Disadvantages of the hashtable
- Unordered Data: An element's order is not guaranteed by hash tables. Arrays can be a better option if you need to keep the components in a certain sequence because they store them consecutively.
- Additional Overhead: The requirement for hash functions, hash buckets, and possible collisions results in additional memory overhead for hash tables.
Summary
This article has taught us that the Hashtable is a type of non-generic collection that we can utilize in our applications to store objects as key-value pairs. The Hashtable class's ability to speed up element retrieval is one of its main advantages. It is important to remember that a hashtable does not have an intrinsic ordering of its elements. Moreover, hashtables are prone to errors because they require no typing. Finally, when compared to dictionaries, hashtables perform worse.
We learned the new technique and evolved together.
Happy coding!