Contravariance Vs Covariance

Covariance Vs Contravariance

Covariance Vs Contravariance


  static void Main()
  {
    ArgumentY oArgumentY = new ArgumentY();
    // In this case, the parameter to IncrA is ReturnX and the parameter to ChangeIt  is
    // ArgumentY.
    // Because of contravariance, the following line is OK.
    ChangeIt oChangeIt = IncrA;
    ReturnX oReturnX = oChangeIt(oArgumentY);
    Console.WriteLine("oReturnX: " + oReturnX.iValue);

    // In the next case, the return type of IncrB is ArgumentY and the return type of
    // ChangeIt is ReturnX.
    // Because of covariance, the following line is OK.
    oChangeIt = IncrB;
    oArgumentY = (ArgumentY) oChangeIt(oArgumentY);
    Console.WriteLine("oArgumentY: " + oArgumentY.iValue);
  }
}

The output from the program is shown here:
oReturnX: 1
oArgumentY: 1



Difference between Contravariance  Vs Covariance, real world scenarios and live code example on Contravariance  and Covariance, use of Contravariance  and Covariance in c # sharp dot .Net