Sometimes it is useful to copy one list contents to another which its type is more general.
Let me emphasize my intent with a small example:
Let there be a Dog, Cat & a Mouse types which inherit from Animal type, and let there be some lists: List<Dog>, List<Cat> & List<Mouse> list that we would like to union to one List<Animal> list in order to perform an general operation on all of the animals objects.
Here’s an example of these classes implementation for clarifying purpose:
We can try adding the specific lists to the general list (e.g.: adding List<Dog> to List<Animal>):
Casting dogs list to List<Animal> is also not allowed.
So we need a way to transform the specific type list to its general type form, something like the following:
In order to enable us to perform the precedes we’ll use the Extension Method feature in .NET 3.5 to extend the List<T> type with the Transform method:
Note how the Transform method signature enforces T type to inherit from K type using the where keyword.
In this post I reviewed a way to transform one typed generic list List<T> to another typed generic list List<K> in case that the type T inherits from the type K and used Extension Method feature to add this capability to the List<T> class.
Hope you’ll find it useful.