title: Statically detect type mismatches in foreach statement
body: <p>I have a large C# code base in which I'm trying to refactor and clean up someone else's tangled code.  I recently stumbled on a chunk like this:</p>
  
  <pre><code>List&lt;Bar&gt; bars = ... ;
  
  ...
  
  foreach (Foo foo in bars) { ... }
  
  ...
  
  public class Bar
  {
      ...
  
      public static explicit operator Foo() { ... }
  }
  </code></pre>
  
  <p>This type mismatch is a problem.  And, as you might expect, the code <em>doesn't</em> actually work:  It's a bug that's been hiding in plain sight for a long time.</p>
  
  <p>However, the code is <em>legal</em>.  Neither Visual Studio 2013 nor ReSharper 2016 complain about this fairly obvious bug:  I had to wait until a runtime exception to discover that the code is broken.  I'd rather find out a lot earlier.</p>
  
  <p>I've poked around both Visual Studio and the ReSharper options trying to find a way to make my tools detect these kinds of type mismatches:  ReSharper's "Code Patterns" is the closest I can get, and while it can recognize the syntax pattern at fault, it doesn't support deep enough type analysis to detect the bug.</p>
  
  <p>So does anyone know of a way to make ReSharper statically detect <code>foreach</code> type mismatches?  Or, alternatively, does anyone know of a tool that can?</p>
  
  <p><strong>Update:</strong>  I omitted originally that there is an <code>explicit</code> custom casting operator from <code>Bar</code> to <code>Foo</code> — that's <code>explicit</code>, mind you, not <code>implicit</code>.  The existence of that cast operator seems to wreak havoc on the tools' ability to detect this issue.  I've updated the code in question to show the behavior.</p>