General collections are certainly preferable because of their expressiveness. One thing to keep in mind when moving from non-generic collections is that sometimes the behavior may be different than expected. For example, using an indexer in a Hashtable and a Dictionary will act differently for values ββthat aren't there. Hashtable will return null while the Dictionary returns.
Hashtable ht = new Hashtable(); ht.Add(1, "one"); string s1 = ht[1; // s1="one" string s2 = ht[2]; // s2=null var dic = new Dictionary<int, string>(); dic.Add(1, "one"); string s1 = dic[1]; // s1="one" string s2 = dic[2]; // throws KeyNotFoundException
A common way to handle this is to use the following technique:
string s = null; if (dic.TryGetValue(k, out s)) {
This will only be displayed at runtime, so itβs worth knowing in advance.
denis phillips
source share