How Generic Types Are Instantiated


One question that is often raised when working with generics is whether the use of generic classes leads to code-bloat at runtime. The simple answer is no. The reason is that C# implements generics in a highly efficient manner that creates new constructed types only when they are needed. Here is how the process works.

When a generic class is compiled into MSIL, it retains all of its type parameters in their generic form. At runtime, when a specific instance of the class is required, the JIT compiler constructs a specific, executable code version of the class in which the type parameters are replaced by the type arguments. Each instance of the class that uses the same type arguments will use the same executable code version.

For example, given some generic class called Gen<T>, all Gen<int> objects will use the same executable code. Thus, code-bloat is reduced and only those versions of the class that are actually used in the program will be created. When a different constructed type is created, a new version of the class is compiled.

In general, a new executable version of a generic class is created for each constructed type in which the type argument is a value type, such as int or double. Thus, each object of Gen<int> will use one version of Gen, and each object of type Gen<double> will use another version of Gen, with each version of Gen tailored to the specific value type. However, there will be only one version of a generic class that handles all cases in which the type argument is a reference type. This is because the size of all references is the same. Thus, only one version is needed to handle all types of references. This optimization also reduces code-bloat.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net