Why does C# (4.0) not allow co- and contravariance in generic class types?

First off, as Tomas says, it is not supported in the CLR.

Second, how would that work? Suppose you have

class C<out T>
{ ... how are you planning on using T in here? ... }

T can only be used in output positions. As you note, the class cannot have any field of type T because the field could be written to. The class cannot have any methods that take a T, because those are logically writes. Suppose you had this feature — how would you take advantage of it?

This would be useful for immutable classes if we could, say, make it legal to have a readonly field of type T; that way we’d massively cut down on the likelihood that it be improperly written to. But it’s quite difficult to come up with other scenarios that permit variance in a typesafe manner.

If you have such a scenario, I’d love to see it. That would be points towards someday getting this implemented in the CLR.

UPDATE: See

Why isn’t there generic variance for classes in C# 4.0?

for more on this question.

Leave a Comment