Advantages of generics
Performance :
One of the big advantages of generics is
performance. Using value types with non – generic collection classes results in
boxing and unboxing when the value type is converted to a reference type and
vice versa.
Using ArrayList class :
ArrayList list = new ArrayList();
list.Add(44); // boxing - convert a value type
to a reference type
int i1 = (int)list[0];
// unboxing - convert a reference type to a value
type
foreach (int
i2 in list)
{
Console.WriteLine(i2); // unboxing
}
Using generics List<T> class :
List < int
> list = new List
< int > ();
list.Add(44); // no boxing - value types are
stored in the List < int >
int i1 = list[0]; // no
unboxing, no cast needed
foreach (int
i2 in list)
{
Console.WriteLine(i2);
}
Type Safety :
Another feature of generics is type safety.
As with the ArrayList class, if objects are used, any type can be added to this
collection. This example shows adding an integer, a string , and an object of
type MyClass to the collection of type ArrayList.
ArrayList list = new ArrayList();
list.Add(44);
stringList.Add("mystring");
list.Add(new MyClass());
Now if this collection is iterated
using the following foreach statement, which iterates using integer elements,
the compiler accepts this code. However, because not all elements in the
collection can be cast to an int, a runtime exception will occur.
foreach (int i in list)
{
Console.WriteLine(i);
}
Errors should be detected as early as
possible. With the generic class List<T>, the generic type T defines what
type are allowed. Which a definition of List<int>, only integer type can
be added to the collection. The compiler doesn't compile this code because the
Add() method has invalid arguments.
List < int > list = new List < int >
();
list.Add(44);
stringList.Add("mystring");// compile time error
list.Add(new MyClass()); // compile time error
Binary Code Reuse :
Generics allow better binary code reuse. A
generic class can be defined once and can be instantiated with many different
types.
List < int
> list = new List
< int > ();
list.Add(44);
List < string
> stringList = new List
< string > ();
stringList.Add("mystring");
List < MyClass > myclassList = new List <
MyClass > ();
myClassList.Add(new MyClass());
Generic types can be defined in one
language and used form any other .NET language.