Posted on 27. February 2008 10:26 by B-Virtual
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.
d0ba3237-823d-4856-bedc-9a286004b96d|0|.0
Tags: c#, generics