Generics
Type safety, Performance and Generality
This articles focal point is generics, which is a new addition in version 2.0 release of Microsoft .Net Framework. This article explains why Generics are valuable and what they can add to your application, exploring the classes in System.Collections.Generic namespace.
The Generic Problem
The first release of Microsoft .NET Framework introduced a System.Collections namespace. The namespace contains number if different interfaces and classes that define various types of helpful container lists, directories and hashtables. Each has a different implementation and serves a distinct and specific purpose. A collection is an example of commonly used class within the namespace. It is a container to which objects of any type can be added. This offers powerful flexibility and adaptability.
Collection also has number of drawbacks, however. All items are stored as objects; this results in an overhead as items are added or removed from the collection because they have to be unboxed and boxed to specific types. The overhead creates a performance penalty each time item in the list or collection is accessed. Given that items in the list and collection often traversed in a loop structure, the performance penalty component really affects the overall performance of your application. Additionally, no type checking enforces consistent use of the same type within the collection at compile time, which can lead to unforeseen runtime errors.
The 1.0 and 1.1 version of Microsoft .Net framework did not have solution for the performance hit for boxing and un-boxing types. The type has to be always cast when accessed from the list. They did offer workaround to enforce consistent type use, tough. The workaround involves writing wrappers around ArrayList and other collections and list types to limit the specific type that can be assigned. This is less than ideal because you end up creating wrapper class for each specific type to use. The result is lot of code and that doesn’t vary a whole lot between the contained types. Even if you employ a code generator- a number will assist you with this- it still amounts to a fair amount of traditional code to maintain.
Collection Based Sample Code
Following sample demonstrate the maintenance problem. It defines a list that has a sample test item as the specific type contains. The example includes sample methods for add and remove functionality that limit the collection to the specific type.
/*
* Sample class to add to lists.
*/
private class TestItem
{
private int _ItemValue = 0;
public int ItemValue
{
get { return this._ItemValue; }
set { this._ItemValue = value; }
}
public TestItem(int itemValue)
{
this.ItemValue = itemValue;
}
}
/*
* Sample collection that is specific to TestItem type.
*/
private class TestItemCollection : CollectionBase
{
public TestItem this[ int index ]
{
get
{
return( (TestItem) List[index] );
}
set
{
List[index] = value;
}
}
public int Add( TestItem itemValue )
{
return( List.Add( itemValue ) );
}
public void Remove( TestItem itemValue )
{
List.Remove( itemValue );
}
}
/*
* Code to demonstrate using our TestItemCollection type.
*/
TestItemCollection testCollection = new TestItemCollection();
// Add some numbers to the list
for( int i = 0; i < 20; i++ )
{
testCollection.Add(new TestItem(i));
}
IEnumerator listEnumerator = testCollection.GetEnumerator();
while( listEnumerator.MoveNext() )
{
Console.WriteLine("{0}", ((TestItem)(listEnumerator.Current)).ItemValue);
}
// Wait so you can read the output
System.Console.ReadLine();
As you can see, the item also must be accessed from the collection. This obligatory cast means that an error would be result if another type of object were put into this collection. The code serves its purpose to create a type safe collection for dealing with the TestItem Class, but it is not reusable of other types. If you have a number of such type-specific classes, maintaining them become so unwieldy that it almost isn’t worth it for the safety provided.
The Generic Solution
Generics were introduced to offer a combination of type safety, performance, and generality in the defined type, which in an all around win. A generics us a type-safe class that declared without a specific type applied to it in the definition. Rather type is specific at the time object is used. In the previous example that would be equivalent to specifying TestItem as the type at the time you declare your collection variables. This would limit that particular item from holding any type other than a TestItem. The code will not compile if you attempt to assign something like such as DataSet. The System.Collection.Generic namespace contains a number of pre-build classes that represent common types, including Following:
Link List – A doubly Link List
List – An array that is dynamically sized as needed
Queue – Represents the first in first out collection objects
Stack – Represent s the Last in First out collection objects
Using existing Generics sample code
The language syntax for generics takes a bit of adjustment (at least it did for me), but in the end the functionality provided far weighs any learning curve necessary to get use to the syntax. In C#, the generic type can be identified by the less than and greater than symbols after the generic type name. The specific type you want to apply to generic type is specific within the symbols. In the example, you simply use the predefined list rather than creating your own generic code:
/*
*Sample use of the Generic List Type
*/
List<TestItem> testCollection=new List<TesItem>();
//add some numbers to the list
for (int i = 0;i < 20; i ++)
{
Testcollection.add(new TestItem(i));
}
Foreach(TestItem test in TestItemCollection)
{
Console.WriteLine(“{0}”,test.Itemvalue);
}
//wait so you can read the output
Console.ReadLine();
If you try to assign an object of any type than TestItem to the TestItemCollection instance above, you receive a compile time error.
Cheers,
nITin