What is Co-Variance and Contra Variance in C#4.0? Explain with example

 Posted by Niladri.Biswas on 7/15/2012 | Category: C# Interview questions | Views: 1863 | Points: 40

Converting from a broader type to a specific type is called co-variance.If B is derived from A and B relates to A, then we can assign A to B. Like A=B. This is Covariance.

Converting from a more specific type to a broader type is called contra-variance. If B is derived from A and B relates to A, then we can assign B to A. Like B= A. This is Contravariance.

Co-variance and contra-variance is possible only with reference types; value types are invariant.

Co-variance is guaranteed to work without any loss of information during conversion. So, most languages also provide facility for implicit conversion. Contra-variance on the other hand is not guaranteed to work without loss of data. As such an explicit cast is required. Though, both are type-safe and will compile perfectly and run. e.g. Assuming dog and cat inherits from animal, when you convert from animal type to dog or cat, it is called co-variance. Converting from cat or dog to animal is called contra-variance, because not all features (properties/methods) of cat or dog is present in animal.

In .NET 4.0, the support for co-variance and contra-variance has been extended to generic types. No now you can apply co-variance and contra-variance to Lists etc. (e.g. IEnumerable etc.) that implement a common interface. This was not possible with .NET versions 3.5 and earlier.

class Fruit { }

class Mango : Fruit { }

class Program
delegate T Func<out T>();
delegate void Action<in T>(T a);

static void Main(string[] args)

// Covariance
Func<Mango> mango = () => new Mango();
Func<Fruit> fruit = mango;
// Contravariance
Action<Fruit> fr = (frt) =>
{ Console.WriteLine(frt); };
Action<Mango> man = fr;

Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response