Search code examples
c#.netinterfaceicollection

Casting ICollection of a concrete type to an ICollection of the concrete type interface


What is the recommended way to cast an ICollection<Bar> to ICollection<IBar> where Bar implements IBar?

Is it as simple as

collection = new List<Bar>();
ICollection<IBar> = collection as ICollection<IBar>?

or is there a better way of doing it?


Solution

  • You have to cast every item in the list and create a new one, for example with Cast:

    ICollection<IBar> ibarColl = collection.Cast<IBar>().ToList();
    

    In .NET 4, using the covariance of IEnumerable<T>:

    ICollection<IBar> ibarColl = collection.ToList<IBar>();
    

    or with List.ConvertAll:

    ICollection<IBar> ibarColl = collection.ConvertAll(b => (IBar)b);
    

    The latter might be a little bit more efficient since it knows the size beforehand.