Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#4.0

Generic List Conversion

5.00/5 (5 votes)
6 Sep 2010CPOL 18.2K  
How to convert a generic List of derived types to a generic list of base types.

The Scenario


You have a base class Mammal and a derived class Dog.


C#
public abstract class Mammal
{
}

public class Dog : Mammal
{
}

You create a list of dogs List<Dog>.


The Problem


You want to have a list of mammals List<Mammal> that is built from the list of dogs. If you try either an implicit or explicit cast you will be told that it isn't possible!


The Solution


This little function will create a list of mammals from a list of dogs.


C#
public static List<TBase> DerivedConverter<TBase, TDerived>(List<TDerived> derivedList)
    where TDerived : TBase
{
    return derivedList.ConvertAll<TBase>(
       new Converter<TDerived, TBase>(delegate(TDerived derived)
       {
           return derived;
       }));
}

To use it:


C#
List<Base> listBase = DerivedConverter<Base, Derived>(listDerived);

In our scenario Base would be Mammal and Derived would be Dog.


You could use the same function for Human, Dolphin, Cat etc, or any other derived class list to base class list without having to write a new converter.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)