Transform List<T> to List<K> where T inherits from K

25 בינואר 2009

2 תגובות

Download ListExtension.cs file :

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.

kick it on

Share it:
הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. שדות החובה מסומנים *

2 תגובות

  1. Ido Flatow25 בינואר 2009 ב 22:27

    In C# 3.0, with the new extension method, you can do something like this:


    Cast is an extension method of Enumerable (don't forget "using System.Linq")

  2. itai26 בינואר 2009 ב 9:14

    Indeed, Cast can be used to perform this operation as well – but as you mentioned, Cast is available on C# 3.0