title: foreach on generic type in C#
body: <p>Given the following struct:</p>
  
  <pre><code>struct Foo : IEnumerable&lt;int&gt;, IEnumerable&lt;string&gt; {
      public IEnumerator&lt;int&gt; GetEnumerator() { yield return 1; }
      public IEnumerator&lt;string&gt; IEnumerable&lt;string&gt;.GetEnumerator() {
          yield return "One"
      }
      public IEnumerator IEnumerable.GetEnumerator() =&gt; GetEnumerator();
  }
  </code></pre>
  
  <p>and the following generic method:</p>
  
  <pre><code>void Bar&lt;TEnum, T&gt;(TEnum iterable) where TEnum : IEnumerable&lt;T&gt; {
      foreach (T item in iterable) Console.WriteLine(item);
  }
  </code></pre>
  
  <p>I tried the following:</p>
  
  <pre><code>Foo foo = new Foo();
  Bar&lt;Foo, int&gt;(foo); //prints 1
  Bar&lt;Foo, string&gt;(foo); //prints One (How does this work)
  foreach(int i in foo) Console.WriteLine(i); //prints 1
  foreach (string s in foo) Console.WriteLine(s); 
  // Error: connot convert from string to int
  </code></pre>
  
  <p>Now my question would be: what code does the Compiler generate, when it evalueates these generics to a certain type? AFAIK the generic type would just be replaced with the concrete type. However as can be seen above, this wouldn't work for this example. So how can the compiler choose the correct type in the foreach? My only guess would be that it adds a cast to it. i.e.:</p>
  
  <pre><code>foreach(string item in (IEnumerable&lt;string&gt;)iterable) ...
  </code></pre>
  
  <p>But I chose to declare the Method like this to avoid a cast. Otherwise I could have just done it like this:</p>
  
  <pre><code>void Bar&lt;T&gt;(IEnumerable&lt;T&gt; iterable) { ... }
  </code></pre>
  
  <p>So I really hope it works without casting...</p>
  
  <p>Edit: My question here is not why I get an error in the last foreach (I know that I can't access explicit interface implementations directly on the type), but how it works in the generic method, which AFAIK should evaluate to the exact same code as the last foreach.</p>