How do generics implement structures?

I thought about it. classes are obviously passed to ptr. I suspect that the structures are transmitted by copying them, but I do not know for sure. (it seems that the waste for the int array has every element a ptr and passes ptrs for ints)

But thinking about this, List<MyStruct> cannot know the size of my structure. What happens when I do this? Are there several copies of "List`1", and every time I use it with a storage size that it doesn't have, it creates a new implementation? (setting for new offsets T and those).

This may make sense since the source will be in the CIL inside the DLL. But I fully guess how this is done? Perhaps a link or page # to ECMA standards?

+6
source share
2 answers

Generics uses the concept of open and closed types: defining a parametric generic class (i.e. List<T> ) is an open generic type that the runtime generates a closed generic type for every different use that you have in your code, etc. e. a different type is created for List<int> , and for List<MyStruct> , for each closed typical type, size and type T known at runtime.

Update from MSDN :

If a generic type or method is compiled into the Microsoft Intermediate Language (MSIL), it contains metadata that identifies it as having type parameters. How MSIL is used for a generic type is used depending on whether the parameter of the supplied type is a value of type or a reference type.

When the first type is the first one constructed with a value type as a parameter, the runtime creates a specialized generic type with the specified parameter or the parameters are replaced with the corresponding location in MSIL. specialized generic types are created once for each unique value type that is used as a parameter.

Generics work a little differently for reference types. The first time a generic type is built with any reference type, the runtime creates a specialized universal type with a reference object, replacing the parameters in MSIL. Then, every time the constructed type is instantiated with the reference type as its parameter, no matter what type it means, the runtime reuses the previously created specialized version of the general type. This is possible because all links are the same size.

+9
source

The CLR compiles 1 version of the generic class and uses it for all types of links. It also compiles 1 version for each value type use to optimize performance.

+2
source

Source: https://habr.com/ru/post/891055/


All Articles