Friday, January 05, 2007

* .NET 2.0 : CSharp Generics

Generics have been introduced in version 2.0 of CSharp language and Common Language Runtime. Generics introduce the concept of type parameters which makes it possible to defer the specification of one or more types of a class or method until the class or method is declared and instantiated by client code.

Consider a following type :

public class GenericClass<T>
public T Field;

GenericClass<string> g = new GenericClass<string>;
g.Field= "Hi There";

In above example the GenericClass implementation does not fix on the type of data it will store but leaves it generic enough for client to decide what to store in GenericClass.

Client at the time of creating an instance of GenericClass specifies which type of data it wants to store.

.NET Framework provides lot of built in collection generic classes in namespace System.Collections.Generics like List, Queue, Stack, etc.

Developers can also develop their own Generic Types.

Its recommended to use Generic Collection classes instead of classes like ArrayList because Generic Classes combine reusability, type safety and efficiency in that most perfect way.

The limitation with non-generic collection classes is that any reference type that is added to an ArrayList is implicitly upcast to Object and any value type must be boxed when added to list and unboxed when retrieved.

When a Generic type is compiled into MSIL, the metadata contains type parameters but how it is used depends upon whether the type used is value or reference type. When a value type is passed CLR creates specialized class out of Generic class for each unique value type passed.

In case of reference types, the first time a generic type is constructed with any reference type, the runtime creates a specialized generic type with object references substituted for the parameters in MSIL. For all the subsequent instance creation CLR uses the same specialized type irrespective of what type it is. This is possible because all references are of same size.

Further Reading : Introduction to Generics

No comments:

Post a Comment