I love the generic Dictionary class. It's located in the System.Collections.Generic namespace. This class is like a strongly-typed hash table (which lets you reference objects as key-value pairs). You can specify the type for the key and another type for the value. This code snippet below shows how to create, add, and retrieve data from a Dictionary. It spares the developer from writing a bunch of extra conversion wrapping code.
public void Dictionary_1()
Dictionary<string, DateTime> group = new Dictionary<string, DateTime>();
//Add based on separate variables
string strKey1 = "abc";
DateTime dt1 = DateTime.Now;
//Add as single line
group.Add("def", new DateTime(2005, 12, 25));
//Should now have 2 items
//Get value given key
DateTime dt2 = group["abc"];
Generics are great. You can also use them for strongly-typed lists, setting the return type of a method, and many other techniques that simplify code.
Post a Comment