Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've read some information about generics in .ΝΕΤ and noticed one interesting thing.

For example, if I have a generic class:

class Foo<T> 
{ 
    public static int Counter; 
}

Console.WriteLine(++Foo<int>.Counter); //1
Console.WriteLine(++Foo<string>.Counter); //1

Two classes Foo<int> and Foo<string> are different at runtime. But what about case when non-generic class having generic method?

class Foo 
{
    public void Bar<T>()
    {
    }
}

It's obvious that there's only one Foo class. But what about method Bar? All the generic classes and methods are closed at runtime with parameters they used with. Does it mean that class Foo has many implementations of Bar and where the information about this method stored in memory?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
103 views
Welcome To Ask or Share your Answers For Others

1 Answer

As opposed to C++ templates, .NET generics are evaluated in runtime, not at compile-time. Semantically, if you instantiate the generic class with different type parameters, those will behave as if it were two different classes, but under the hood, there is only one class in the compiled IL (intermediate language) code.

Generic types

The difference between different instantiatons of the same generic type becomes apparent when you use Reflection: typeof(YourClass<int>) will not be the same as typeof(YourClass<string>). These are called constructed generic types. There also exists a typeof(YourClass<>) which represents the generic type definition. Here are some further tips on dealing with generics via Reflection.

When you instantiate a constructed generic class, the runtime generates a specialized class on the fly. There are subtle differences between how it works with value and reference types.

  • The compiler will only generate a single generic type into the assembly.
  • The runtime creates a separate version of your generic class for each value type you use it with.
  • The runtime allocates a separate set of static fields for each type parameter of the generic class.
  • Because reference types have the same size, the runtime can reuse the specialized version it generated the first time you used it with a reference type.

Generic methods

For generic methods, the principles are the same.

  • The compiler only generates one generic method, which is the generic method definition.
  • In runtime, each different specialization of the method is treated as a different method of the same class.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...