How are generic methods generated in C #?

Suppose I have a general method:

void Fun<T>(FunArg arg) {} 

Are this.Fun<Feature> and this.Fun<Category> different instances of a common method?

In general, how is the general method generated? Does a different general argument create a different method or the same method along with the different metadata used at runtime?

Please support your answer with some quotes from the language specification.

Also, suppose I did this:

 client.SomeEvent += this.Fun<Feature>; //line1 client.SomeEvent += this.Fun<Category>; //line2 client.SomeEvent += this.Fun<Result>; //line3 

and then,

 client.SomeEvent -= this.Fun<Feature>; //lineX 

Does lineX thing I did in line1 ? Or does it depend on something else?

+6
source share
3 answers

It depends on the types used.

For all reference types (e.g. classes), one method will be JITted to handle all of them.

For all types of values ​​(i.e. structures), one method for will be JITted.

Thus, the information in the question is not detailed enough to answer, if Feature and Category are reference types, then yes, they will use the same JIT method. If one of them or both are value types, one method for the value type will be JITted.

Check out my use of the word jitted here. There will be only one method in the assembly assembled, but at run time, JITTER will create the actual implementations of the general methods in accordance with the above rules.

Pop Quiz What happens if you use NGEN on an assembly with common types / methods? (hint: not what you think )

+4
source

They all use the definition of a method, but at run time they differ MethodInfo - because arguments of a general type define a generic method.

Supporting illustration:

  Action<FunArg> a1 = Fun<X>; Action<FunArg> a2 = Fun<Y>; Action<FunArg> a3 = Fun<Y>; Console.WriteLine(a1.Method == a2.Method); // false Console.WriteLine(a3.Method == a2.Method); // true 

At the JIT level, this is more complicated; any parameters of the reference type will share the implementation, since the reference link is a link (noting that all such T must satisfy any restrictions in advance). If value-type T exists, then each combination of generic type arguments gets a separate implementation at runtime, since each requires a different final implementation.

+5
source

Yes, they will become two separate methods.

0
source

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


All Articles