Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an Interface collection

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

like image 344
abenci Avatar asked Jan 28 '10 13:01

abenci


1 Answers

Try using a generic method:

void AddCars<T>(IEnumerable<T> collection) where T : IPainting
like image 57
Nick Craver Avatar answered Sep 29 '22 07:09

Nick Craver