Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting a generic collection to base type

I've got an IList<DerivedClass> that I want to cast to ICollection<BaseClass> but when I attempt an explicit cast, I get null. Is it possible to do this without creating and populating a new collection?

Edit: Since I only want to read from the collection, I switched to using a generic method:

public void PopulateList<BaseClass>(ICollection<T> collection)

Then I can pass it an IList<DerivedClass>. Is there a good way to cache this list so I can refresh it when I need to. My first inclination is to use:

Object cachedCollection;
Type cachedType;
public void PopulateList<BaseClass>(ICollection<T> collection) {
    cachedCollection = collection;
    cachedType = T;

    // other stuff...
}

private void Refresh() {
    PopulateList<cachedType>(cachedCollection as ICollection<cachedType>);
}

Does anyone have a better way of doing this?

like image 354
dmo Avatar asked Feb 11 '09 23:02

dmo


1 Answers

The short answer is "No." You would need to create a new collection with the new BaseClass type and populate it.

If you think about it, it makes sense. If you could simply "cast" your collection to BaseClass, you could then stick something that was of type "BaseClass" into it, thereby forcing a simple BaseClass object into a DerivedClass Collection. This would defeat the purpose creating a Collection with Type-Safety.

In the extreme case, if you had two derived classes, Foo and Bar, you could force Bar objects into a collection of Foo objects by type-casting the collection back to a collection of BaseClass.

like image 161
Doug Avatar answered Sep 23 '22 17:09

Doug