Cast of collections

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.
 
P

Peter Morris

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.
 
K

kieninternetservice

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.
 
S

Stefan L

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
 
P

Pavel Minaev

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top