C#: A lack of covariance with generics example

One of the things I find most confusing when reading about programming languages is the idea of covariance and contravariance and while I’ve previously read that covariance is not possible when using generics in C# I recently came across an example where I saw that this was true.

I came across this problem while looking at how to refactor some code which has been written in an imperative style:

I thought the compiler would infer that I actually wanted a collection of ‘IFoo’ given that I was returning from the method directly after the call to Select but it doesn’t.

As I understand it the reason that we can’t downcast an IEnumerable of ‘Foo’ to an IEnumberable of ‘IFoo’ is that we would run into problems if we worked of the assumption that our original collection only contained Foos in it later on in our program.

For example it would be possible to add any item which implemented the ‘IFoo’ interface into the collection even if it wasn’t a ‘Foo’: