Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How generic methods gets instantiated in C#?

Suppose I've a generic method as:

void Fun<T>(FunArg arg) {}

Are this.Fun<Feature> and this.Fun<Category> different instantiations of the generic method?

In general, how does the generic method get instantiated? Different generic argument produces different method, or same method along with different metadata which is used at runtime?

Please support your answer with some quote(s) from the language specification.

Also, suppose I did these:

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

then later on,

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

Does the lineX undo the thing which I did at line1? Or it depends on somethig else also?

like image 358
Nawaz Avatar asked Apr 23 '12 10:04

Nawaz


People also ask

What is the correct way of defining a generic method?

Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.

Can we create a generic method inside a non generic class?

Yes, you can define a generic method in a non-generic class in Java.


1 Answers

They all share a method definition, but at runtime they are different MethodInfo - because the generic type arguments 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, it is more complex; any reference-type parameters will share an implementation, as a reference is a reference is a reference (noting that all such T must satisfy any constraints in advance). If there are value-type T, then every combination of generic type arguments gets a separate implementation at runtime, since each requires a different final implementation.

like image 174
Marc Gravell Avatar answered Oct 09 '22 02:10

Marc Gravell