Search code examples
asp.netc#-4.0dotnetnukecovariancecontravariance

Real world use of Contravariance and Covariance in .net


I Want to know the real world scenario where we use Contravariance and Covariance with program.I saw various blogs but I am still confused where I can implement.


Solution

  • Have you ever written a foreach? If you have then you have used Covariance so that is the real world usage. You can use foreach on any type which implements IEnumerable. Here is the signature for IEnumerable:

    public interface IEnumerable<out T> : IEnumerable
                                 ^^
                                 ||
                        // See the above out keyword
    

    That out keyword is for covariance so it applies only to return types.

    Have you ever used the IComparable interface, then you have used contravariance. Here is the signature:

    public interface IComparer<in T>
                               ^^
                               ||
                       // See the above in keyword
    

    That in keyword is for contravariance so it applies only to parameter types of the members of the interface.

    And if the out and in keywords are missing then it applies to both input parameter and return parameters. That is called invariance.