Casting a generic collection to another generic collection when the generic types are related

Is there a way for me to cast Collection<C> to Collection<ICar> when I know that C is constrained to inherit from ICar

This code doesn't compile: "Cannot convert type 'System.Collections.ObjectModel.Collection<C>' to 'System.Collections.ObjectModel.Collection<ICar>"

class GenericCollectionManager<C> where C : ICar
{

private Collection<C> myConnections;

Collection<ICar> Connections
{

get {
return (Collection<ICar
>) myConnections;
}

}

}



Answer this question

Casting a generic collection to another generic collection when the generic types are related

  • Drummos

    No you cannot do this; unlike arrays generic collections are not covariant in C# (though I believe the CLR does support it). With arrays if B derives from A then it implies that B[] derives from A[] - this is covariance. With generics the behaviour is different so Collection<B> has no relationship to Collection<A>.

    One of the main drivers for this is performance, as if you return a collection of ICar then there is runtime checking needed to ensure that you are not inserting an ICar of a concrete type different to the underlying collection declaration.



  • pmanisekaran

    You can simulate covariance in a way: http://www.gregbeech.com/Blog/Entry.aspx b=1&id=23

    But there's no way to make them appear covariant, no.



  • Sanju35

    That’s disappointing…. Seems like something that should work… Back to the drawing board…

    Thanks Greg!


  • hye_heena

    Hi Greg,

    I am trying to do something similar... is there an alternative approach to do this

    Thanks,

    G


  • Casting a generic collection to another generic collection when the generic types are related