Tuesday, July 24, 2007

Generics

C# Generics :



Generics are a new feature in version 2.0 of the C# language and the common language runtime (CLR). Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.
It is like a C++ template.



VC++.NET 2005 supports both generics and templates..NET generics differ from C++ templates.
difference is that specialization of a .NET generic class or method occurs at runtime whereas specialization occurs at compile time for a C++ template.

Key differences between generics and C++ templates:


Generics are generic until the types are substituted for them at runtime. Templates are specialized at compile time so they are not still parameterized types at runtime


The common language runtime specifically supports generics in MSIL. Because the runtime knows about generics, specific types can be substituted for generic types when referencing an assembly containing a generic type. Templates, in contrast, resolve into ordinary types at compile time and the resulting types may not be specialized in other assemblies.


Generics specialized in two different assemblies with the same type arguments are the same type. Templates specialized in two different assemblies with the same type arguments are considered by the runtime to be different types.


Generics are generated as a single piece of executable code which is used for all reference type arguments (this is not true for value types, which have a unique implementation per value type). The JIT compiler knows about generics and is able to optimize the code for the reference or value types that are used as type arguments. Templates generate separate runtime code for each specialization.


Generics do not allow non-type template parameters, such as





template C {}. Templates allow them.


Generics do not allow explicit specialization (that is, a custom implementation of a template for a specific type). Templates do.


Generics do not allow partial specialization (a custom implementation for a subset of the type arguments). Templates do.


Generics do not allow the type parameter to be used as the base class for the generic type. Templates do.


Generics do not allow type parameters to have default values. Templates do.


Templates support template-template parameters (e.g.

template class X> class MyClass ), but generics do not.

0 comments: