- In C#, Dictionary is a generic collection which is generally used to store key/value pairs. Dictionary is defined under System.Collection.Generics namespace.
- It is dynamic in nature means the size of the dictionary is growing according to the need.
- A Hashtable is a collection of key/value pairs that are arranged based on the hash code of the key. Or in other words, a Hashtable is used to create a collection which uses a hash table for storage. It is the non-generic type of collection which is defined in System.Collections namespace. In Hashtable, key objects must be immutable as long as they are used as keys in the Hashtable.
static public void Main()
{
// Creating a dictionary
// using Dictionary<TKey, TValue> class
Dictionary<string, string> My_dict =
new Dictionary<string, string>();
// Adding key/value pairs in the Dictionary
// Using Add() method
My_dict.Add("a.01", "C");
My_dict.Add("a.02", "C++");
My_dict.Add("a.03", "C#");
foreach (KeyValuePair<string, string> element in My_dict)
{
Console.WriteLine("Key:- {0} and Value:- {1}",
element.Key, element.Value);
}
Console.ReadLine();
}
static public void Main()
{
Hashtable my_hashtable = new Hashtable();
// Adding key/value pair in the hashtable
// Using Add() method
my_hashtable.Add("A1", "Welcome");
my_hashtable.Add("A2", "to");
my_hashtable.Add("A3", "GeeksforGeeks");
foreach (DictionaryEntry element in my_hashtable)
{
Console.WriteLine("Key:- {0} and Value:- {1} ",
element.Key, element.Value);
}
Console.ReadLine();
No comments