Operation could destabilize the runtime?

I found this entry while looking for my own solution to "operation could destabilize the runtime". While the covariance/contra-variance advice above looks very interesting, in the end I found that I get the same error message by running my unit tests with code coverage turned on and the AllowPartiallyTrustedCallers assembly attribute set.

Removing the AllowPartiallyTrustedCallers attribute caused my tests to run fine. I could also turn off code coverage to make them run but that was not an acceptable solution.

Hopefully this helps someone else who makes it to this page trying to find a solution to this issue.


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.