C++ templates have come to C#! The 1.2 version of the framework and the product currently known as Whidbey (Visual Studio 8) have a new feature that lets you build classes that can accept and work with any type of data.
The idea is simple: Take a class such as a simple Queue object and be able to use strong-typed objects in the class. That sounds easy enough, but to do this using the 1.0 or 1.1 versions of the framework, you would need to write a new Queue object for each type or do casting to object types and back to your type. You would need to rely on Hashtables, Stacks, Queues, and so forth always returning the base type object of Object. With generics, this is no longer necessary. You write one class that takes a parameterized value, and that type will be used throughout the class. Generics increase the usability of your code greatly and add the coolest feature to the language. The 1.2 version of C# will have new generic versions of the common collection classes, such as Hashtable, Queue, and so on.
Generics support one or multiple parameters of types. This means that you can do something like the following:
public class MyDictionary<KeyType, ValType>
Generics also support the idea of constraints. These constraints are implemented using the where keyword after defining the types in <>. You can declare one or multiple constraints per parameter. The basic idea is that you can specify which types you will to allow to be passed to the parameters. Here is an example of using constraints:
public class MyDictionary<KeyType, ValType> where KeyType : IComparable, KeyType : IEnumerable, ValType : MyProduct
With generics, value type and reference type parameters are handled as follows:
For each type passed as parameter that is a value type, the runtime will generate a specific instance of that class, with the specific type being substituted for the parameter that was passed.
When you pass a reference type, the runtime will produce one instance of the class and use that instance for every instance of the generic class created.
The following example demonstrates the use of generics.
using System; namespace Client.Chapter_5___Building_Your_Own_Classes { public class MyQueue<ItemType> { private ItemType[] items; //Adds an item to the queue public void Enqueue(ItemType data) { //Do stuff } //Removes an item from the queue public ItemType Dequeue() { return items[0]; } } class MyServer { [MTAThread] static void Main(string[] args) { MyQueue<MyProduct> queue = new MyQueue<MyProduct>(); queue.Enqueue(new MyProduct()); MyProduct c = queue.Dequeue(); } } public class MyProduct { } }