title: C# covariance confusion
body: <p>The following is a code snippet about covariance in C#. I have some understanding about how to <em>apply</em> covariance, but there is some detailed technical stuff that I have hard time grasping.</p>
  
  <pre><code>using System;
  namespace CovarianceExample
  {
      interface IExtract&lt;out T&gt; { T Extract(); }
      class SampleClass&lt;T&gt; : IExtract&lt;T&gt;
      {
          private T data;
          public SampleClass(T data) {this.data = data;}   //ctor
          public T Extract()                               // Implementing interface
          {
              Console.WriteLine
                  ("The type where the executing method is declared:\n{0}",
                  this.GetType() );
              return this.data;
          }
      }
      class CovarianceExampleProgram
      {
          static void Main(string[] args)
          {
              SampleClass&lt;string&gt; sampleClassOfString = new SampleClass&lt;string&gt;("This is a string");
              IExtract&lt;Object&gt; iExtract = sampleClassOfString;
  
              // IExtract&lt;object&gt;.Extract() mapes to IExtract&lt;string&gt;.Extract()?
              object obj = iExtract.Extract();
              Console.WriteLine(obj);                  
              Console.ReadKey();
          }
      }
  }
  
  // Output:
  // The type where the executing method is declared:
  // CovarianceExample.SampleClass`1[System.String]
  // This is a string
  </code></pre>
  
  <p>Invoking <code>IExtract&lt;object&gt;.Extract()</code> invokes <code>IExtract&lt;string&gt;.Extract()</code>, as evidenced by the output. While I kind of expected this behavior, I am not able to tell myself why it behaved the way it did.</p>
  
  <p><code>IExtract&lt;object&gt;</code> is <code>NOT</code> in the inheritance hierarchy containing <code>IExtract&lt;string&gt;</code>, except the fact that C# made <code>IExtract&lt;string&gt;</code> assignable to <code>IExtract&lt;object</code>>. But <code>IExtract&lt;string&gt;</code> simply does <strong>NOT</strong> have a method named <code>Extract()</code> that it inherits from <code>IExtract&lt;object&gt;</code>, unlike the <em>normal</em> inheritance. It doesn't appear to make much sense to me at this time.</p>
  
  <p>Would it be sensible to say that <code>IExtract&lt;string&gt;</code>'s <strong>OWN</strong> coincidentally (or by design) similarly named <code>Extract()</code> method hides <code>IExtract&lt;object</code>>'s <code>Extract()</code> method? And that it is a kind of a hack? (Bad choice of word!)</p>
  
  <p>Thanks</p>