0

I have read a good article introducing the covariance and contracovariance

http://bartdesmet.net/blogs/bart/archive/2009/04/15/14377.aspx

Contravariant parameters should only occur in input positions: method parameters, set-only properties or indexers.

class SubClass : BaseClass {
    public void PrintSubClass() {}
}
class BaseClass{
}

static class Sample {

    public static void PrintMeNow (SubClass c)
    {
        c.PrintSubClass();
    }
}

static void Main(string[] args)
{
    SubClass  sc = new SubClass();
    BaseClass bc = new BaseClass();

    Sample.PrintMeNow(sc); // ok
    Sample.PrintMeNow(bc); // Line A (not-ok Question: Is this contravariance?)
}

Based on my understanding of the contravariance, I have put the code as above. Obviously, the line A is not correct and I mis-interpret the concept of contravariance.

Which part is wrong? What concept is not understood correctly? How to make it right?

svick
  • 236,525
  • 50
  • 385
  • 514
q0987
  • 34,938
  • 69
  • 242
  • 387

1 Answers1

3

Covariance and contravariance are about generic parameters; your code has nothing to do with it.

It doesn't work because bc isn't a SubClass.
All SubClasses are BaseClasses, but not all BaseClasses are SubClasses.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • @Slakes, From the above URL "In other words, we’re getting in a more derived type for the event arguments but we treat it as less derived. As the argument appears in an input position, this is safe to do". This is the place that really confuses me. There we can assign a method with base class signature to another method with derived class signature. – q0987 Jun 03 '11 at 21:57
  • 1
    In other words, he's passing a derived type where it expects a base type. That's the opposite of what you're doing. – SLaks Jun 03 '11 at 22:04
  • Specifically, he's passing a `ProgressEventArgs` as an `EventArgs`. – SLaks Jun 03 '11 at 22:10