Downcast a generic List<T> to a base type

27. February 2008

Sometimes it is usefull to downcast a specific List<T> to a List of object that T inherited from, like an interface or so. This is the way to get the job done. 

We start with the following piece of code:

   1: // your class definition
   2: public class AlfaRomeoCar : ICar
   3: {  
   4:   ...
   5: }
   6:  
   7: // A method that only accepts List<ICar>
   8: public static List<Part> LoadAllCarPartsWithSerial(List<ICar> cars)
   9: {
  10:   ...
  11:   return resultList
  12: } 
  13:  

 

But what do we do if we need to supply a List<AlfaRomeoCar> to the LoadAllCarPartsWithSerial(List<ICar>) method? Well we can downcast the objects in the list to the base interface to use it as a parameter.

   1: List<ICar> cars = alfaCars.ConvertAll(List<AlfaRomeoCar>.DownCast<AlfaRomeoCar, ICar>());

 

And here is the DownCast converter method:

   1: public static Converter<T, U> DownCast<T, U>() where T : U
   2: { 
   3:   return delegate(T item) { return (U)item; };
   4: }

 

Et voila,I hope this helps.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Development ,