Downcasting a list of objects in C#

Farinha picture Farinha · Mar 8, 2011 · Viewed 8.4k times · Source

How can I downcast a list of objects so that each of the objects in the list is downcast to an object of a derived class?

This is the scenario.

I have a base class with a List of base items, and two classes inheriting from it:

public class BaseClass
{
    public List<BaseItem> items;
    protected BaseClass()
    {
        // some code to build list of items
    }
}
public class DerivedClass : BaseClass
{
    public DerivedClass : base() {}
}
public class AnotherDerivedClass : BaseClass
{
    public AnotherDerivedClass : base() {}
}

public class BaseItem {}
public class DerivedItem : BaseItem {}
public class AnotherDerivedItem : BaseItem {}

The idea is to not have to duplicate the code needed to build the list of items. The BaseItem has all the basic stuff I need, and I can always downcast BaseItem to one of the derived items.

The problem arises when I have a list of them. The List of BaseItem is declared in the BaseClass because all the derived classes have to have it. But when accessing it at runtime I can't seem to be able to downcast to the derived class.

Answer

Jakub Konecki picture Jakub Konecki · Mar 8, 2011

Using LINQ:

    var baseList = new List<BaseClass>();
    var derivedList = baseList.Cast<DerivedClass>();

Note: Having to downcast usually is a 'smell' and indicates that the inheritance hierarchy is wrong, or wrongly implemented. The idea of having a base class is that you can treat all subclasses as superclass without having to downcast to individual subclass types.

Instead of Cast you might want to use OfType to 'fish out' certain derived classes from a collection of superclasses. But again, there should be no need to do that.

Ask yourself, why you need to have a subclass - maybe you need to move some functionality to base class?