Interface type parameter covariance and contravariance in C#

  • I would like this blog post to serve as a quick reference that recalls the basic concept of covariant and contravariant type parameters of generic interfaces in the C# language.
  • I tried to keep the example as simple as possible. Included comments explain the key points. No long stories and no dissertations.
  • The code does nothing, but compiles on C# 4.0 or newer compiler.
  • Try deleting the first slash character in the first line to kind of switch between the snippets (BTW this is cool trick 🙂 ).
//*
  // T is covariant
  // Implicit conversion from interface instance I<B> which has a method with RETURN type B
  // that is MORE derived than specified in target interface I<A>
  public interface I<out T> { T foo(); }
  public class IImp<T> : I<T> { public T foo() { return default(T); } }
  public class A { }
  public class B : A { }

  class Program
  {
    static void Main(string[] args)
    {
      I<A> ia = new IImp<B>();
    }
  }
/*/
   // T is contravariant
   // Implicit conversion from interface instance I<A> which has a method with ARGUMENT type A
   // that is LESS derived than specified in target interface I<B>
   public interface I<in T> { void foo(T t); }
   public class IImp<T> : I<T> { public void foo(T t) { } }
   public class A { }
   public class B : A { }

   class Program
   {
     static void Main(string[] args)
     {
       I<B> ia = new IImp<A>();
     }
   }
//*/

One comment

  1. Interface type parameter covariance and contravariance in C# | PJSen Blog…

    Dziękujemy za dodanie artykułu – Trackback z dotnetomaniak.pl…

Leave a Reply

Your email address will not be published. Required fields are marked *

Protection against spam * Time limit is exhausted. Please reload CAPTCHA.