C# vs Java generics. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

C# vs Java generics.

Whenever I see some posts online comparing Java and C#, I generally see people claiming that the java implementation of generics is not as good as C#'s implementation. What's substandard in java generics as compared to C# generics?

15th Apr 2018, 8:57 PM
Rusty.Metal
2 Answers
+ 6
The thing I personally dislike most is type erasure, which is part of Java by design. That is to say, inside a generic class Foo<T> I cannot gather information about what type T is, because at compile time all type annotations are erased. In C# I can do typeof(T) no problem and in Java I can't. This leads to many weird workarounds if you actually need to know the type of your type parameter, like class MyGeneric<T>{ Class<T> clazz; MyGeneric(Class<T> clazz){ this.clazz = clazz; } } and then having to pass this clazz thing along. String myThing = "hello"; Class clazz = myThing.getClass(); new MyGeneric<String>(clazz); very clazzy. Another odd thing about Java generics is that you can't use primitive types (int, boolean, etc) as template parameters. That's probably why we have int and Integer, boolean and Boolean, etc. in Java. Just a really bad design decision imo...
15th Apr 2018, 9:12 PM
Schindlabua
Schindlabua - avatar
+ 6
Thank you Schindlabua, now I'm clear (:
15th Apr 2018, 9:13 PM
Rusty.Metal