Click here to Skip to main content
Click here to Skip to main content

Generic List Conversion

By , 6 Sep 2010
 

The Scenario

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

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.

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:

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)

About the Author

DaveyM69
United Kingdom United Kingdom
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralGood job! The DerivedConverter method could be a bit simple...memberKubajzz6 Sep '10 - 2:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 6 Sep 2010
Article Copyright 2010 by DaveyM69
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid