Cast of collections

  • Thread starter Thread starter Dansk
  • Start date Start date
D

Dansk

Hi all,

I have a class A, and onother class B that inherits from A (class B : A).

I also have a collection of B : Collection<B>

Is there a clean way to see the Colection<B> as a Collection<A> ?


The only thing I see at the moment is to copy all the elements of the
Collection<B> into a new Collection<A>.

Thanks in advance

Dansk.
 
The only thing I see at the moment is to copy all the elements of the
Collection<B> into a new Collection<A>.

Currently there is no mechanism for casting.
 
Hi all,

I have a class A, and onother class B that inherits from A (class B : A).

I also have a collection of B : Collection<B>

Is there a clean way to see the Colection<B> as a Collection<A> ?

The only thing I see at the moment is to copy all the elements of the
Collection<B> into a new Collection<A>.

Thanks in advance

Dansk.

If you can cast each member of one class to that of another, then
finally you can cast the class itself to another class.
 
Hi,

depending on what you need it for, it might help you to consider
declaring the function you call in a different way:

public static int BinSearch(IList<IComparable> coll) // needs cast of
collection
public static int BinSearch<T>(IList<T> coll) where T:IComparable //
does not need casts

If this is not possible you may want to write a wrapper class that casts
the elements on access.

Third way is using the .Cast() method for enumerables. But I can't tell
you what it is really doing (maybe it's similar to way 2.)


HTH,
Stefan
 
Hi all,

I have a class A, and onother class B that inherits from A (class B : A).

I also have a collection of B : Collection<B>

Is there a clean way to see the Colection<B> as a Collection<A> ?

This is a FAQ. No, there's no such mechanism, because it can be
unsafe. For example, if we're speaking of the standard Collection<T>
class, then that has an Add(T) method. Let's imagine that C# allowed
you to cast Collection<B> to Collection<A>, while referring to the
same object:

class A { ... }
class B : A { ... }
class C : A { ... }

Collection<B> cb = new Collection<B>();
Collection<A> ca = cb; // seemingly ok
ca.Add(new C()); // types are all valid, but now our collection of
Bs contain an C!

So, no. For IEnumerable<T> it would actually be a safe cast, and C#
4.0 will allow you to do that. Meanwhile, for IEnumerable
specifically, you can use Enumerable.Cast(). For other (mutable)
collection types, it is inherently type-unsafe for the reasons
described above.
 
Back
Top