
.NET 2.0+Generic Types (2)
Microsoft introduced generics to the .NET framework with version 2.0. Generic programming allows highly reusable classes to be created without specifying the types that they operate upon. These types are only provided when the class is used.
Dictionary<TKey, TValue>
Another useful generic collection is Dictionary<TKey, TValue>. This is similar to the Hashtable class, in that it stores a key and a value for each element in the collection and allows a value to be retrieved quickly using the key as a lookup. It also demonstrates that a generic type may include more than one type parameter. In this case, the key types and value types are declared using the TKey and TValue type parameters respectively. In the example below, integers are used for the keys and strings for the values.
Dictionary<int, string> items = new Dictionary<int,string>();
items.Add(50, "Hello");
items.Add(99, "world");
string extracted = items[99];
Creating a Generic Class
To create a generic class, you simply add one or more type parameters to the class definition. When using several type parameters, separate them with commas. Type parameters are often named with a single, upper case letter. However, this is not a requirement and names can be made longer and more meaningful.
In this section we will create a simple generic class that holds a pair of values or objects. The held items will be of a type specified when the class is used so we will use a type parameter, in this case named "T". To declare the class, add the following code:
Whenever you need to use a value that is of the undeclared type, it can now be referenced using T. For example, to add the properties that hold the two values, add the following code. Note that the types of the properties and their backing stores use the unspecified type T.
T _firstItem;
T _secondItem;
public T FirstItem
{
get { return _firstItem; }
set { _firstItem = value; }
}
public T SecondItem
{
get { return _secondItem; }
set { _secondItem = value; }
}
When creating a constructor for a generic type, you can use the type parameter to define the types of incoming parameters where required.
public Pair(T firstItem, T secondItem)
{
FirstItem = firstItem;
SecondItem = secondItem;
}
Finally, we can add a method to the class that we will use to show the contents of the Pair<T>. The following overrides to ToString method to combine and return the values:
public override string ToString()
{
return string.Format("{0} | {1}", _firstItem, _secondItem);
}
You can now use the Pair class with any type. The sample below shows the results of Pair instances containing integers and strings.
Pair<int> integers = new Pair<int>(1, 2);
Console.WriteLine(integers);
Pair<string> strings = new Pair<string>("Hello", "world");
Console.WriteLine(strings);
/* OUTPUT
1 | 2
Hello | world
*/
11 April 2010