I mostly use Java and generics are relatively new. I keep reading that Java made the wrong decision or that .NET has better implementations etc. etc.
So, what are the main differences between C++, C#, Java in generics? Pros/cons of each?
locked by animuson♦ Dec 5 '13 at 17:10
This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center.
closed as too broad by animuson♦ Dec 5 '13 at 17:10
There are either too many possible answers, or good answers would be too long for this format. Please add details to narrow the answer set or to isolate an issue that can be answered in a few paragraphs.If this question can be reworded to fit the rules in the help center, please edit the question.
I'll add my voice to the noise and take a stab at making things clear:
C# Generics allow you to declare something like this.
and then the compiler will prevent you from putting things that aren't
The benefit of this is that it makes it really fast. There's no casting or any other stuff, and because the dll contains the information that this is a List of
The downside of this is that old C# 1.0 and 1.1 code (before they added generics) doesn't understand these new
Java Generics allow you to declare something like this.
On the surface it looks the same, and it sort-of is. The compiler will also prevent you from putting things that aren't
The difference is what happens behind the scenes. Unlike C#, Java does not go and build a special
The benefit of this approach is that old code which doesn't understand generics doesn't have to care. It's still dealing with the same old
The downside is the speed hit I mentioned previously, and also because there is no
C++ Templates allow you to declare something like this
It looks like C# and Java generics, and it will do what you think it should do, but behind the scenes different things are happening.
It has the most in common with C# generics in that it builds special
Both C# and Java produce output which is designed for virtual machines. If you write some code which has a
C++ produces raw x86 binary code. Everything is not an object, and there's no underlying virtual machine which needs to know about a
Because of this, the C++ compiler places no restrictions on what you can do with templates - basically any code you could write manually, you can get templates to write for you.
In C# and Java, the generics system needs to know what methods are available for a class, and it needs to pass this down to the virtual machine. The only way to tell it this is by either hard-coding the actual class in, or using interfaces. For example:
That code won't compile in C# or Java, because it doesn't know that the type
And then you have to make sure the things you pass to addNames implement the IHasName interface and so on. The java syntax is different (
The 'classic' case for this problem is trying to write a function which does this
You can't actually write this code because there are no ways to declare an interface with the
C++ suffers from none of these problems. The compiler doesn't care about passing types down to any VM's - if both your objects have a .Name() function, it will compile. If they don't, it won't. Simple.
So, there you have it :-)
C++ rarely uses the “generics” terminology. Instead, the word “templates” is used and is more accurate. Templates describes one technique to achieve a generic design.
C++ templates is very different from what both C# and Java implement for two main reasons. The first reason is that C++ templates don't only allow compile-time type arguments but also compile-time const-value arguments: templates can be given as integers or even function signatures. This means that you can do some quite funky stuff at compile time, e.g. calculations:
This code also uses the other distinguished feature of C++ templates, namely template specialization. The code defines one class template,
Template specialization is important for C++ because it allows for structural differences in data structures. Templates as a whole is a means of unifying an interface across types. However, although this is desirable, all types cannot be treated equally inside the implementation. C++ templates takes this into account. This is very much the same difference that OOP makes between interface and implementation with the overriding of virtual methods.
C++ templates are essential for its algorithmic programming paradigm. For example, almost all algorithms for containers are defined as functions that accept the container type as a template type and treat them uniformly. Actually, that's not quite right: C++ doesn't work on containers but rather on ranges that are defined by two iterators, pointing to the beginning and behind the end of the container. Thus, the whole content is circumscribed by the iterators: begin <= elements < end.
Using iterators instead of containers is useful because it allows to operate on parts of a container instead of on the whole.
Another distinguishing feature of C++ is the possibility of partial specialization for class templates. This is somewhat related to pattern matching on arguments in Haskell and other functional languages. For example, let's consider a class that stores elements:
This works for any element type. But let's say that we can store pointers more effciently than other types by applying some special trick. We can do this by partially specializing for all pointer types:
Now, whenever we instance a container template for one type, the appropriate definition is used:
Anders Hejlsberg himself described the differences here "Generics in C#, Java, and C++".
There are already a lot of good answers on what the differences are, so let me give a slightly different perspective and add the why.
As was already explained, the main difference is type erasure, i.e. the fact that the Java compiler erases the generic types and they don't end up in the generated bytecode. However, the question is: why would anyone do that? It doesn't make sense! Or does it?
Well, what's the alternative? If you don't implement generics in the language, where do you implement them? And the answer is: in the Virtual Machine. Which breaks backwards compatibility.
Type erasure, on the other hand, allows you to mix generic clients with non-generic libraries. In other words: code that was compiled on Java 5 can still be deployed to Java 1.4.
Microsoft, however, decided to break backwards compatibility for generics. That's why .NET Generics are "better" than Java Generics.
Of course, Sun aren't idiots or cowards. The reason why they "chickened out", was that Java was significantly older and more widespread than .NET when they introduced generics. (They were introduced roughly at the same time in both worlds.) Breaking backwards compatibility would have been a huge pain.
Put yet another way: in Java, Generics are a part of the Language (which means they apply only to Java, not to other languages), in .NET they are part of the Virtual Machine (which means they apply to all languages, not just C# and Visual Basic.NET).
Compare this with .NET features like LINQ, lambda expressions, local variable type inference, anonymous types and expression trees: these are all language features. That's why there are subtle differences between VB.NET and C#: if those features were part of the VM, they would be the same in all languages. But the CLR hasn't changed: it's still the same in .NET 3.5 SP1 as it was in .NET 2.0. You can compile a C# program that uses LINQ with the .NET 3.5 compiler and still run it on .NET 2.0, provided that you don't use any .NET 3.5 libraries. That would not work with generics and .NET 1.1, but it would work with Java and Java 1.4.
Follow-up to my previous posting.
Templates are one of the main reasons why C++ fails so abysmally at intellisense, regardless of the IDE used. Because of template specialization, the IDE can never be really sure if a given member exists or not. Consider:
Now, the cursor is at the indicated position and it's damn hard for the IDE to say at that point if, and what, members
It gets worse. What if
After a bit of thinking, a programmer would conclude that this code is the same as the above:
Wrong. At the point where the compiler tries to resolve this statement, it doesn't actually know
Now, the code compiles. To see how ambiguities arise from this situation, consider the following code:
This code statement is perfectly valid and tells C++ to execute the function call to
Both Java and C# introduced generics after their first language release. However, there are differences in how the core libraries changed when generics was introduced. C#'s generics are not just compiler magic and so it was not possible to generify existing library classes without breaking backwards compatibility.
For example, in Java the existing Collections Framework was completely genericised. Java does not have both a generic and legacy non-generic version of the collections classes. In some ways this is much cleaner - if you need to use a collection in C# there is really very little reason to go with the non-generic version, but those legacy classes remain in place, cluttering up the landscape.
Another notable difference is the Enum classes in Java and C#. Java's Enum has this somewhat tortuous looking definition:
(see Angelika Langer's very clear explanation of exactly why this is so. Essentially, this means Java can give type safe access from a string to its Enum value:
Compare this to C#'s version:
As Enum already existed in C# before generics was introduced to the language, the definition could not change without breaking existing code. So, like collections, it remains in the core libraries in this legacy state.
11 months late, but I think this question is ready for some Java Wildcard stuff.
This is a syntactical feature of Java. Suppose you have a method:
And suppose you don't need to refer to the type T in the method body. You're declaring a name T and then only using it once, so why should you have to think of a name for it? Instead, you can write:
The question-mark asks the the compiler to pretend that you declared a normal named type parameter that only needs to appear once in that spot.
There's nothing you can do with wildcards that you can't also do with a named type parameter (which is how these things are always done in C++ and C#).
The biggest complaint is type erasure. In that, generics are not enforced at runtime. Here's a link to some Sun docs on the subject.
C++ templates are actually much more powerful than their C# and Java counterparts as they are evaluated at compile time and support specialization. This allows for Template Meta-Programming and makes the C++ compiler equivalent to a Turing machine (i.e. during the compilation process you can compute anything that is computable with a Turing machine).
In Java, generics are compiler level only, so you get:
Note that the type of 'a' is an array list, not a list of strings. So the type of a list of bananas would equal() a list of monkeys.
So to speak.
Looks like, among other very interesting proposals, there is one about refining generics and breaking backwards compatibility:
NB: I don't have enough point to comment, so feel free to move this as a comment to appropriate answer.
Contrary to popular believe, which I never understand where it came from, .net implemented true generics without breaking backward compatibility, and they spent explicit effort for that. You don't have to change your non-generic .net 1.0 code into generics just to be used in .net 2.0. Both the generic and non-generic lists are still available in .Net framework 2.0 even until 4.0, exactly for nothing else but backward compatibility reason. Therefore old codes that still used non-generic ArrayList will still work, and use the same ArrayList class as before. Backward code compatibility is always maintained since 1.0 till now... So even in .net 4.0, you still have to option to use any non-generics class from 1.0 BCL if you choose to do so.
So I don't think java has to break backward compatibility to support true generics.