Hejlsberg on C# generics

Jan. 31st, 2004 | 03:56 am

Artima continues to publish Anders Hejlsberg's interviews. This time, Hejlsberg talks of generics (parameterised types) and how the C# design and implementation of generics differs from that of Java and C++.

Java generics are purely a compile-time hack. The VM doesn't know about generic types. So a List of Strings is still a List of Objects as far as the VM is concerned. This makes generics pretty much useless for pure run-time stuff—like reflection. The other disadvantage is that since the same representation is used for primitives as well as objects, a List of ints is also a List of Objects, the conversion between int and Object (called “boxing”) being an overhead. C# is closer to C++ templates in this regard.

Hejlsberg points out that C++'s strong typing can be circumvented using templates, whereas C# still does strong type-checking on generic types. I wrote a little useless program to prove this to myself:

Program… )

Here, you can have an A of B as well as an A of C. You can have an A of any type as long as the type has a const function called “bar” that takes no arguments.

By the way, LJ needs to have something like Slashdot's ecode tag. I had to run the sample program code through this filter before pasting it into my post:

s/&/\&/g
s/</\&lt;/g
s/>/\&gt;/g


And I had to run the above 3 lines through the filter too :-) What the heck!

#