Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do C# generic methods on a non-generic class boil down to?

If I have a class like this: -

static class Foo {
   public static void Bar<T>(T item) { Console.WriteLine(item.ToString(); }
}

I know that in this example it's unnecessary to use T since all Types have ToString() on them etc. - it's simply a contrived example. What I'm more interested in is what happens under the bonnet in terms of the following: -

Foo.Bar("Hello");
Foo.Bar(123);
Foo.Bar(new Employee("Isaac"));

I broadly (think!) I understand reification i.e. if you make different types of a generic class e.g.

List<Int32>
List<String>
List<Employee>

etc. then at compile-time (or runtime?) we end up with three actual concrete types, one for each generic argument specified. Does the same apply to method calls in my first example i.e. would we still have a single class Foo but three reified Bar methods, one for String, Int32 and Employee?

like image 684
Isaac Abraham Avatar asked Dec 11 '12 16:12

Isaac Abraham


1 Answers

This is where the difference between C++ templates and C# generics comes into play.

In C++, templates cause a new method to be generated for each type it is used with. In C#, however, the code in the method is only created once. The same code runs whether you call it with an int, string, or object type parameter.

Because C# generics remain generic when compiled, they can be exposed in compiled libraries without need for re-compilation. In C++, you are required to include the original template in your consuming code, so a new copy can be compiled.

Simply put, you only get one compiled method per generic method.

like image 110
Kendall Frey Avatar answered Nov 15 '22 17:11

Kendall Frey