Generics in C# 2.0


Generics are simply placeholders for actual types. Generics are defined with left and right brackets: <T> In other words Generics allow you to define type-safe data structures, without committing to actual data types. .Net 2.0 provides number of generic collection classes for lists, stacks, queues, dictionaries.

Generics Benefits:

Generics in .NET let you reuse code and the effort you put into implementing it. The types and internal data can change without causing code bloat, regardless of whether you are using value or reference types. You can develop, test, and deploy your code once, reuse it with any type, including future types, all with full compiler support and type safety. Because the generic code does not force the boxing and unboxing of value types, or the down casting of reference types, performance is greatly improved. With value types there is typically a 200 percent performance gain, and with reference types you can expect up to a 100 percent performance gain in accessing the type (of course, the application as a whole may or may not experience any performance improvements). The source code available with this article includes a micro-benchmark application, which executes a stack in a tight loop. The application lets you experiment with value and reference types on an Object-based stack and a generic stack, as well as changing the number of loop iterations to see the effect generics have on performance.

Let us create console application to have actual understanding.

 

In visual studio 2005 create new project >>Console Application Name it as "GenericsLists".

 

We will add class called as "Customer" to this console application as below:

 

public class Customer

{

     private int custId;

     public Customer(int Id)

     {

          this.custId = Id;

     }       

     public override string ToString()

     {

          return custId.ToString();

     }

}

 

With any of the console application we will have something called as "Program.cs"

Which will be some thing like this:

 

public class Program

{

     static void Main()

     {

          //Type safe list (of Customer objects)

          List<Customer> custList = new List<Customer>();

          //Type safe list (of integers)

          List<int> intList = new List<int>();

          //Populate the Lists

          for (int i = 0; i < 5; i++)

          {

              custList.Add(new Customer(i + 100));

              intList.Add(i * 5);               

          }

          //Integer list

          foreach (int i in intList)

          {

              Console.Write("{0} ", i.ToString());

          }

          Console.WriteLine("\n");

          //Print the Customer List

          foreach (Customer Customer in custList)

          {

              Console.Write("{0} ", Customer.ToString());

          }

          Console.WriteLine("\n");

     }

}

 

The Customer class contains a single private field (custId), a constructor, and an override of ToString to return the custId field as a string.

 

First you create an instance of List that will hold Customer objects. The type of custList is "List of customer Objects" and is declared as:

 

List<Customer> custList = new List<Customer>();

 

The definition List<T>, the T is a placeholder for the actual type you'll place in that list.

 

if you try to add an integer to the list of Customer ie. custList.Add (i * 5);

In this case you will get two erros as:

 

  • The best overloaded method match for 'System.Collections.
    Generic.List<ListCollection.Customer>.Add(ListCollection.Customer)' has some invalid arguments.

  • Argument '1': cannot convert from 'int' to 'ListCollection.Customer'.

Here it is not possible to implicit conversion of int to collection of Customer object or subtype one type implicit conversion to another type is not legal.

 

You can store types in a type sage collection. Thus collection of customer will hold "Sales" object if Sales derived from Customer.

 

Command line output:

    0 5 10 15 20

    100 101 102 103 104 


Recommended Free Ebook
Similar Articles