Reputation: 1517
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?
Upvotes: 4
Views: 5619
Reputation: 23324
You cannot cast to ICollection<IBar>
, but you can cast to IEnumerable<IBar>
.
So if you don't intend to add something to the list, you can do this:
IEnumerable<IBar> enumeration = (IEnumerable<IBar>)collection;
The solutions from the other answers don't actually cast but create a new list that will not reflect subsequent changes to the original list.
Upvotes: 2
Reputation: 460208
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.
Upvotes: 3
Reputation: 5946
Just convert all entries with
ICollection<IBar> ibars = collection.ConvertAll(bar => (IBar)bar);
I think this variant is also readable. Perhaps there are ways to cast it with more performance...
Upvotes: 0