IList<IWhatever> as a method parameter

c#, generics, interface

Solution

C# generics are invariant. It means `List<string>` is not a `List<object>`.

C# 4.0 introduces safe covariance/contravariance but still, you wouldn't be able to pass `List<string>` as `List<object>`. The reason is:

List<string> x = new List<string>();
List<object> o = x; // assume this statement is valid
o.Add(5); // Adding an integer to a list of strings. Unsafe. Will throw.

Arrays, on the other hand are covariant. You can pass a `string[]` to a method that expects `object[]`.

Problem

I have two `IList<ICat>` and I'm trying to create a method which takes an `IList<ICat>` and does some work. I'm having problems trying to pass either an `IList<PussyCat>` or `IList<OtherCat>` to it, both `PussyCat` and `OtherCat` implement `ICat`. I've tried: ``` List<PussyCat> cats = ... DoWork((IList<ICat>)cats); ``` and just ``` DoWork(cats); ``` But neither compile. Any ideas?

Original source