Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type erasure: Java vs C# [duplicate]

Possible Duplicate:
C# vs Java generics

Java use Type erasure while C# keep type information at runtime, what are the practical difference in the behaviors of the language from this design?

like image 223
Ryan Avatar asked Oct 20 '12 15:10

Ryan


People also ask

Is erasure specific to Java?

The way to implement generics, the Java compiler applies type erasure to: Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.

Does C# use type erasure?

C# does not have type erasure. C# has actual generic types deeply baked into the runtime.

Does C++ have type erasure?

Type Erasure is achieved in C++ by encapsulating a concrete implementation in a generic wrapper and providing virtual accessor methods to the concrete implementation via a generic interface.


1 Answers

There are a lot of issues with type erasure. It brings back bad memories. I haven't used Java since 1.6, so this may be out of date, but some things I remember:

  1. You can't create a new T (or do anything that requires knowing what type T actually is)
  2. Generic lists can't create an array of T
  3. You can't use int, float, etc in generics with Java
    1. This has performance and memory implications because you always have to use the heap versions (Integer, etc)
  4. You can't implement a generic interface with two different Ts, e.g. class c implements IComparable<MyClass>, IComparable<MyOtherClass> is impossible.
    1. More practically, you can't overload methods with different generic types, e.g. by taking in List<T1>, List<T2>, and so on. For example, Java -- How to deal with type erasure in constructors?
  5. Everything is done by casting and boxing
like image 117
Mark Sowul Avatar answered Sep 24 '22 13:09

Mark Sowul