Contrary to other answers, this isn't supported in .NET 4.0. Only interfaces and delegates support generic variance. However, .NET 4.0 would allow you to do this:
void AMethod(IEnumerable<A> parameter) {}
...
List<B> list = new List<B>();
AMethod(list);
In .NET 3.5 you can get much the same thing to work with the aid of Cast
:
void AMethod(IEnumerable<A> parameter) {}
...
List<B> list = new List<B>();
AMethod(list.Cast<A>());
Another alternative is to make AMethod
generic:
void AMethod<T>(List<T> parameter) where T : A
...
List<B> list = new List<B>();
AMethod(list); // Implicitly AMethod<B>(list);
That may or may not do what you need - it depends on what you do within AMethod
. If you need to add new items of type A
, you'll have problems - and rightly so. If you only need to get items out of the list, that would be fine.