Fact checking for my talk

Chris Wright via Digitalmars-d digitalmars-d at puremagic.com
Sat Aug 13 10:27:35 PDT 2016


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.


More information about the Digitalmars-d mailing list