Basically Collections
& Generics are useful in handling group of Objects.In .net,all the
collections objects comes under the interface IEnumerableWhich
inturn has ArrayList(Index -Value)) & HashTable(Key- Value).After .net
framework 2.0,ArrayList & HashTable were replaced with List &Dictionary .Now the Arraylist & HashTable are
no more used in now a days projects.
Coming to difference between HashTable & Dictionary,Dictionary is generic whereas Hastable is not Generic.We can add any type of object to HashTable ,but while reteriving we need to Cast it to the required Type.So it is not type safe.But to dictionary,while declaring itself we can specify the type of Key & Value ,so no need to cast while retreiving.Let me explain it with an Example.
HashTable Program:
class HashTableProgram
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht.Add(1,"One");
ht.Add(2,"Two");
ht.Add(3,"Three");
foreach (DictionaryEntry de in ht)
{
int Key = (int)de.Key; //Casting
string value = de.Value.ToString(); //Casting
Console.WriteLine( Key + " " + value);
}
}
Dictionary Example
class DictionaryProgram
{
static void Main(string[] args)
{
Dictionary<int,string> dt = new Dictionary<int,string>();
dt.Add(1,"One");
dt.Add (2,"Two");
dt.Add (3,"Three");
foreach (KeyValuePair<int,String> kv in dt)
{
Console.WriteLine( kv.Key + " " + kv.Value);
}
}
}
Coming to difference between HashTable & Dictionary,Dictionary is generic whereas Hastable is not Generic.We can add any type of object to HashTable ,but while reteriving we need to Cast it to the required Type.So it is not type safe.But to dictionary,while declaring itself we can specify the type of Key & Value ,so no need to cast while retreiving.Let me explain it with an Example.
HashTable Program:
class HashTableProgram
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht.Add(1,"One");
ht.Add(2,"Two");
ht.Add(3,"Three");
foreach (DictionaryEntry de in ht)
{
int Key = (int)de.Key; //Casting
string value = de.Value.ToString(); //Casting
Console.WriteLine( Key + " " + value);
}
}
Dictionary Example
class DictionaryProgram
{
static void Main(string[] args)
{
Dictionary<int,string> dt = new Dictionary<int,string>();
dt.Add(1,"One");
dt.Add (2,"Two");
dt.Add (3,"Three");
foreach (KeyValuePair<int,String> kv in dt)
{
Console.WriteLine( kv.Key + " " + kv.Value);
}
}
}
No comments:
Post a Comment