lundi 23 novembre 2015

Why are generic type definitions in C# not equatable to those they inherite from

I had expected the following test to pass, but it doesn't.

var iCollectionType = typeof(ICollection<>);
var listSuper = typeof(List<>).GetInterfaces().First(i => i.GUID == iCollectionType.GUID);
Assert.That(listSuper, Is.EqualTo(iCollectionType));

I know that the same type loaded in 2 different app domains aren't considered equal. I don't see how that could be happening in the above code, but I checked the AssemblyQualifiedName of each type, and sure enough they're different.

iCollectionType.AssemblyQualifiedName.Dump();
//System.Collections.Generic.ICollection`1, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

listSuper.AssemblyQualifiedName.Dump();
//null

When I tested further I found that this is the case for all generic interfaces in the list of interfaces for a generic type definition, and also for generic base types; but not for non-generic interfaces and base types, nor for constructed generic types.

I'd like to know why generic type definitions I get using typeof seem to be incompatible with those in their inheritance and base type list. It seems less than awesome.

The closest I've come to finding an answer was on the Type.AssemblyQualifiedName page of MSDN where I found the following quote.

If the current Type object represents a generic parameter, this property returns null.

I'm fairly sure that doesn't apply here since I don't think these are generic parameters, but I could be wrong.

The above was running in LinqPad v5.02.03 if that makes a difference.





Aucun commentaire:

Enregistrer un commentaire