Generics in .NET 2.0

by nitin 16. September 2008 15:13
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

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

ASP.NET | C#

Comments

10/21/2008 6:56:52 AM

this is one of the good article i have come across

zuo hr

11/3/2009 4:53:45 AM

Thank you for your help!

fast personal loans us

11/3/2009 5:15:04 AM

Nice post . keep up the good work

personal loans us

11/4/2009 2:28:05 PM

Interesting post

paydayloans us

11/16/2009 3:46:38 AM

Yea nice Work !Laughing

cash loans us

12/17/2009 5:50:28 PM

I completely agree with the above comment, the internet is with a doubt growing into the most important medium of communication across the globe and its due to sites like this that ideas are spreading so quickly.

travel deals us

12/18/2009 5:24:52 PM

Well, this is my first visit to your blog! We are a group of volunteers and starting a new initiative in a community in the same niche. Your blog provided us valuable information to work on. You have done a marvellous job!

Garlic Sauce Recipes us

Add comment


 

  Country flag

biuquote
  • Comment
  • Preview
Loading



Quote

Never Believe what the lines of ur hand predict about your future,because people who dont hve hands also have a future... Believe in urself!!!

Cheers,
Nit

My Pages

Recent posts

Recent comments

Comment RSS

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my view in anyway.

© Copyright 2008