Big Bucket Software you like to use
One Size Fits All
November 5th, 2006

I might be way off here, but Generics (in C#) aren’t really that fantastic. The way I see it – Templates are powerful whereas Generics are like syntactic sugar. Okay, that’s unfair. They’re a particularly useful form of syntactic sugar that save you from having to write umpteen strongly typed collections and what have you, but they’re nowhere near as useful as templates. Here’s why…

Templates (in C++) can be seen as a way to implement message passing. That is, at compile time, if the object that you specify as your template argument knows how to respond to all the messages being called on it, your program will compile. With Generics, the template argument is typed. That is, you can’t just start throwing method calls at your object; you need to specify an interface with those methods on it.

So what do Generics buy you? Well, as I said, you don’t need to write strongly typed collections. But what if you don’t write strongly typed collections? Well, Generic’s save you from all those painful runtime casts to turn your Object into your ParticularObject. And well, that’s about it. I guess it’s something, but when I first heard the term “Generics” I thought it was just some fancy new term that just meant Templates. I was very wrong.

  • In Java you are absolutely correct, Java generics are just syntactic sugar checked at compile time and thrown out.

    C# generics are a bit more interesting than you give them credit for, albeit certainly not quite C++ Templates. In .NET Generics are first-class citizens of the CLR and so .NET Generics constraints are checked not just at compile time, but at run time as well (in a much faster “short circuit” way than directly reflecting for it yourself).

    The biggest benefit of C# Generics is removing a lot of implicit boxing of value types, which can do a lot to save cycles/memory. (A Generic using a value type uses that value type directly instead of boxing it into a capital-named sibling reference type (C# int boxed in System.Int32).)

    But, you are right that Generics are not (and are not meant to be) Templates. They have similar syntaxes and solve similar, but not the same, problems.

  • Microsoft basher!