Operation could destabilize the runtime?

I believe it is an issue of covariance or contravariance as noted by this forum post.

See Covariance and Contravariance in C#, Part Two: Array Covariance and the rest of the Covariance and Contravariance series at Eric Lippert’s blog.

Although he is dealing with Arrays in the article I linked, I believe a similar problem presents itself here. With your first example, you are returning an IEnumerable that could contain objects that implement an interface that is larger than ISomeTable (i.e. – you could put a Turtle into an Animals IEnumerable when that IEnumerable can only contain Giraffes). I think the reason it works when you return IQueryable is because that is larger/wider than anything you could return, so you’re guaranteed that what you return you will be able to handle(?).

In the second example, OfType is ensuring that what gets returned is an object that stores all the information necessary to return only those elements that can be cast to Giraffe.

I’m pretty sure it has something to do with the issues of type safety outlined above, but as Eric Lippert says Higher Order Functions Hurt My Brain and I am having trouble expressing precisely why this is a co/contravariant issue.

Leave a Comment