Monday, June 8, 2015

Covariance and Contravariance

Covariance and Contravariance are one of the commonly used concepts OOPS. And it is implemented well by Dot Net framework. Here we will discuss it with the help of C#.

Covariance

An object that is instanciated with more derfive type argument is assigned to an object instanciated with less derived type arguments.


      IEnumerable<string> str = new List<string>();

In the above code snippet an object of a list type is assigned to an more derived type i.e. IEmumerable. This an example of Covariance. 

Contravariance

An object is instenciated with less derived type arguments is assign to object with more derive type argument.


        
      static void SetObject(Object o)
      {
            //some code
      }

      Action<object> obj = SetObject;
      Action<string> obj1 = obj; 


Here in this example a static method is assigned to an Action<object> type delegate. Then again the Action<object> type delegate is assign to an Action<string> type delegate which is quite possible. By this we instenciated an object with less derived type arguments is assign to object with more derive type arguments. This is what Contravariance is.

Happy Coding ... :)