user11937
user11937

Reputation:

Casting ReadOnlyCollection<derivedType> to ReadOnlyCollection<baseType>

I was wondering if anyone could point me in the right direction...

How do I cast from ReadOnlyCollection<myDerivedType> to ReadOnlyCollection<myBaseType> without iterating or "newing up" a copy?

I am using .NET Framework 4.0

Upvotes: 5

Views: 1358

Answers (6)

Eric Lippert
Eric Lippert

Reputation: 660289

You can implicitly convert a ROC<Derived> into an IEnumerable<Base> in C# 4, but not into a ROC<Base>.

That is unfortunate; it would be really nice to be able to do covariant conversions on immutable types.

Upvotes: 11

Jacob Stanley
Jacob Stanley

Reputation: 4824

You can't do this, so you're probably better off passing around interfaces like IEnumerable<T> or ICollection<T> instead of concrete classes like ReadOnlyCollection<T>.

Then you can do, as others have suggested:

collection.Cast<myBaseType>();

Upvotes: 0

Rune FS
Rune FS

Reputation: 21752

You can't you will have to project ReadOnlyCollection<myDerivedType> into ReadOnlyCollection<myBaseType>

Upvotes: 0

Tomasz Jaskuλa
Tomasz Jaskuλa

Reputation: 16033

I don't think that covariance and contravariance is allowed in C# for generic types. Generics don’t support this—they’re invariant.

I think that only generic delegates in C#4 has limited support for covariance and contravariance.

Upvotes: 0

George Duckett
George Duckett

Reputation: 32438

I don't believe you can, as the generic parameter T isn't defined as an out (as has been pointed out .net doesn't support Covariance and Contravariance in classes).

ReadOnlyCollection<T>

You would have to use LINQ, such as readOnlyColl.Cast<myBaseType>();, or a loop. Internally LINQ would use a loop / iteration, making a new copy.

Upvotes: 1

ub1k
ub1k

Reputation: 1674

with Linq

yourCollection.Cast<myBaseType>();

Upvotes: 0

Related Questions