Collections& Genericssão úteis para manipular grupos de objetos. No .NET, todos os objetos de coleções IEnumerableficam sob a interface , que por sua vez possui ArrayList(Index-Value))& HashTable(Key-Value). Após o .NET framework 2.0, ArrayList& HashTableforam substituídos por List& Dictionary. Agora, o Arraylist& HashTablenão é mais usado nos projetos atuais.
Chegando à diferença entre HashTable& Dictionary, Dictionaryé genérico onde, como Hastablenão é genérico. Podemos adicionar qualquer tipo de objeto HashTable, mas durante a recuperação, precisamos convertê-lo no tipo necessário. Portanto, não é do tipo seguro. Mas dictionary, enquanto se declara, podemos especificar o tipo de chave e valor, portanto, não há necessidade de converter durante a recuperação.
Vejamos um exemplo:
HashTable
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);
}
}
}
Dicionário,
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);
}
}
}