Passing an Interface collection
c#, collections, generics, interface
Solution
C# 4 will not allow the code that you wrote, since the method `AddCars` expects an `IEnumerable<Car>` which implements `IPainting`. This does not mean that you can pass any class implementing `IPainting` (you could for instance have a `class Bike : IPainting` that has nothing to do with the `Car` class whatsoever. However, it will allow the other way around; if you have `void AddCars(IEnumerable<IPainting> collection)` you can pass a `List<Car>` to the method.
Until then, you will need to stick to passing `Car` sequences to the method, by using some casting mechanism (such as `painting.Cast<Car>()` suggested in other answers).
Problem
Suppose you have the following class: ``` class Car : IPainting { ... } ``` Then a function like this: ``` void AddCars(IEnumerable<Car> collection) ``` Then a code snippet like this: ``` Car bmw = new Car(); Car mercedes = new Car(); IPainting a = (IPainting) bmw; IPainting b = (IPainting) mercedes; IPainting[] paintings = new IPainting[] {a, b}; AddCars(paintings); // fails to compile ``` This of course doesn't compile because the AddCars() method accepts only a collection of Cars but it is what the 'paintings' array is made of. I know that C# 4.0 will probably provide a solution for this. Is there any workaround today for it? Thanks, Alberto