7

I've been digging in covariance and contravariance in C# and there is one thing I could not manage to understand. C# (AFAIK, as of 4 version) allows one to declare the covariant or contravariant interfaces and delegates using out and in keywords. However, the declaration of the abstract class with such keywords is not possible. Could anyone share an idea about why it was made so? I understand general issues and problems with covariance and contravariance, LSP and so on. However, I was not able to come up with an idea about why the abstract class is not semantically suitable for being covariant or contravariant, whilst interface is.

Here's a sample of the abstract class just for the sake of completeness. It won't compile.

public abstract class SomeList<out T> where T : class
{

}
  • 1
    Why do you ask about abstract classes? I don't see any difference between concrete and abstract classes as far as the problems with co-variance are concerned. – CodesInChaos Feb 12 '16 at 12:52
  • One complication is that you need to forbid mutable generic fields for covariance. Same for readonly fields with a contravariant or invariant generic parameter. – CodesInChaos Feb 12 '16 at 12:53
3

Covariance and contravariance are not allowed in any class. As abstract classes can have concrete implementation, this applies to them too. The short answers for why is that (a) the CLR doesn't support it and (b) it doesn't support it, because (for covariance):

[a class C<T>] cannot have any method that takes a T, any property of type T with a setter, or any field of type T, because fields are logically the same as property setters; T goes in [only]

and therefore the class would have to be fully immutable. Likewise, a contravariant class could not allow a method that returns T or a property of type T with a getter, ie the data could not be got out of it. This limits the usefulness of allowing it (over just allowing it in interfaces) so that it's not worth the effort of making the CLR support this idea.

Please see this answer to another question by Eric Lippert for more details (quote above is from that answer).

  • Thanks, I've probably used the wrong wording when I was trying to search for it. I enjoy Eric's posts very much and often look through them, however I didn't see this one. – Vlad Stryapko Feb 12 '16 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.