Monday, August 18, 2008

Dictionary Object : Generics Collection

In C# using .Net 2.0+, there is now built-in support for Generics collections using the System.Collections.Generic namespace. I use the List type most often, as a strongly-typed substitute for the ArrayList. Since it is strongly-typed, you now have design-time type-checking for enumerations like this (no casting necessary):

List Foos = new List();
foo.Add(new foo(1));
foo.Add(new foo(2));
foreach (foo f in Foos) {
Console.PrintLine(f.ToString());
}


The second-most useful Generic (in my opinion) is Dictionary. This is a strongly-typed hashtable, where you can determine the types of both X (the Key) and Y (the Value). Like other Generic collections, the Dictionary object type is also Enumerable (meaning that you can use statements like foreach to automatically parse its contents in order). However you call an strongly-typed enumeration statement like foreach by referencing each pair of values as a KeyValuePair object and can be performed as follows (ref)

Dictionary EmpAges = new Dictionary();
EmpAges .Add("Amy", "20");
EmpAges .Add("Ben", "25");
foreach(KeyValuePair emp in EmpAges)
{
Console.PrintLine(emp.Key + "\t" + emp.Value);
}

No comments: