简体   繁体   中英

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 ie if you make different types of a generic class eg

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 ie would we still have a single class Foo but three reified Bar methods, one for String, Int32 and Employee?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM