Here are my classes definitions:
public abstract class AbstractEntity : ...
public partial class AbstractContactEntity : AbstractEntity, ...
public sealed class EntityCollectionProxy<T> : IList<T>, System.Collections.IList
where T : AbstractEntity
Now I get an object from a delegate and I want to cast it, and it doesn’t work as I expect it to.
var obj = resolver.DynamicInvoke (this.entity);
var col = obj as EntityCollectionProxy<AbstractEntity>;
obj is of type EntityCollectionProxy<AbstractContactEntity>.
But col is null.
If I try the regular casting (var col = (Entity...) obj) I get an exception.
I would expect that it work since the types are coherent.
What do I miss?
They are not the same types. It is the same as with
List<string>andList<int>: They also can’t be casted to one another. ThatAbstractContactEntityis aAbstractEntitydoesn’t change this.Extracting an interface from
EntityCollectionProxy<T>and making it covariant doesn’t work either, because you want to implementIList<T>which means you have input paramaters and return values of typeTwhich prevents covariance.The only possible solution is the following:
colwill be of typeIEnumerable<AbstractEntity>. If you want to have aEntityCollectionProxy<AbstractEntity>, you need to create a new one:This assumes that your
EntityCollectionProxy<T>class has a constructor that accepts anIEnumerable<T>.But beware, this will be a NEW instance and not the same as returned by
resolver.DynamikInvoke.