Comparison of programming languages (associative array): Difference between revisions

Content deleted Content added
C#: aligned with other examples.
Line 55:
===C#===
<source lang=CSharp>
Dictionary<intstring, string> dic = new Dictionary<intstring, string>();
Hashtable ht = new Hashtable();
htdic.Add("testKeySally Smart", "AssociatedData555-9999");
dic.Add(7"John Doe", "Bond555-1212");
MessageBox.Show((string) ht["testKey"]);
dic.Add("J. Random Hacker", "553-1337");
</source>
 
// access an phone number and display it in a message box
<source lang=CSharp>
MessageBox.Show((string) htdic["testKeySally Smart"]);
Dictionary<int, string> dic = new Dictionary<int, string>();
</source>
dic.Add(7, "Bond");
MessageBox.Show(dic[7]);
</source>
 
The dictionary can also be initialized with all entries during construction. This is called "object initialization".
In the above sample the <code>Hashtable</code> class is only capable of associating a <code>String</code> key with a value of <code>Object</code> type. Because in .NET all types (except [[Pointer (computer programming)|pointer]]s) ultimately derive from <code>Object</code>, anything can be put into a <code>Hashtable</code>, even data of different types. This could lead to errors if consuming code expects data to be of a singular type. In the above code casting is required to convert the Object variables back to their original type. Additionally, casting value-types (structures such as integers) to <code>Object</code> to put into the <code>Hashtable</code> and casting them back requires boxing/unboxing which incurs both a slight performance penalty and pollutes the heap with garbage. This changes in C# 2.0 with generic hashtables called dictionaries. There are significant performance and reliability gains to these strongly typed collections because they do not require boxing/unboxing or explicit type casts and introduce compile-time type checks. C# 3.0 adds a shorthand notation for the dictionary initialization:
<source lang=CSharp>
Dictionary<intstring, string> dic = new Dictionary<intstring, string> {
{
{"Sally Smart", "555-9999"},
{"John Doe", "555-1212"},
{"J. Random Hacker", "553-1337"}
{ 7, "Bond" };
</source>
 
A foreach loop can enumerate through the entire collection. There is no guarantee of order. If order matters the programmer could choose to use a SortedDictionary or use a .Sort linq extension method.
<source lang=CSharp>
// loop through the collection and display each entry
Dictionary<int, string> = new Dictionary<int, string> {
foreach(KeyValuePair<string,string> kvp in dic)
{ 7, "Bond" }
{
};
MessageBox.Show(String.Format("Phone number for {0} is {1}", kvp.Key, kvp.Value);
};
</source>