On Saturday, 13 August 2016 at 17:27:35 UTC, Chris Wright wrote:
On Sat, 13 Aug 2016 16:28:57 +0000, deadalnix wrote:
C# use generic (aka type erasure) for objects
Incorrect:
---
public class Foo {}
var fooList = new List<Foo>();
var objectList = (List<object>)(object)fooList;
---
This throws InvalidCastException. Which isn't possible with
type erasure. The equivalent Java code will not throw an
exception because, after type checking, List<T> is converted to
List<Object>. That's the definition of type erasure.
Similarly, you can inspect the methods on List<Foo> at runtime
in C# and see that, for instance, the `Add` method takes a
parameter of type Foo. And you can look at the type of
`fooList` with reflection and see that it's List with generic
parameter 0 set to Foo. That's stuff you can't do with type
erasure.
The code that .NET generates for a generic instantiation with
class type is different from the code it generates for a
generic instantiation for a struct simply because structs are
not like classes.
I guess what he meant is that there will be just one code
generation, as all class types are just pointers. So on this side
it behaves like Java (if we only talk about reference types).
The difference is that the .NET IL retains complete type
information for the variables, even if it dispatches to the same
instantiation.