Some hints on how different JAVA generics appear to be to .NET generics
A tss entry caught my curiosity as it was talking about a “generics puzzle” in JAVA. Finally, I thought, an example-based look at how JAVA generics differ from their .NET pendant? Indeed, the puzzle turns out to not be one in e.g. C#.
If the intent is to be able to create instances of a provided type argument, we need a constrain on the provided type argument to provide a parameterless constructor…
Beware, though that if T has no default constructor, construction will fail with a MissingMethodException. Funny enough though, the Activator’s method has no constraint on T, which it could easily implement:
Apart from that you could also construct types that have no default constructor. Just sprinkle in some reflection. The type in question is easily accessed with typeof(T)…
What you don’t get with this approach is type safety, and you’ll probably have a performance penalty, but that’s another subject. So, no puzzles to be seen…