Downcast a generic List<T> to a base type

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.

Tags: ,

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading


Björn Bailleul

Web application engineer and developer interested in creating customer centric applications build for ease of use and efficiency. My experience goes from intranet applications to widely used service websites, product portfolios and e-commerce websites.

Specialties

C#, MVC, AJAX, ASP.NET, SQL Server, SQL Reporting Services, WCF, XML, HTML, JavaScript, CSS, Web Services, Scrum, ...

View Bjorn Bailleul's profile on LinkedIn

Month List