title: Why does this code cause Excel to not close properly?
body: <p>Why does this line of code cause Excel not to exit?</p>
  
  <pre><code>Excel.Range range = (Excel.Range)ws.Cells[1,1];
  </code></pre>
  
  <p>If it's because of the casting, then wouldn't this code cause the same problem?</p>
  
  <pre><code>Excel.Worksheet ws = (Excel.Worksheet)wb.ActiveSheet;
  </code></pre>
  
  <p>I've tried. But this works. Excel will close.</p>
  
  <p>If I use this code. Excel closes.</p>
  
  <pre><code>Excel.Range range = ws.get_Range("A1","A1");
  </code></pre>
  
  <p>So what's the difference? Yes I know there's like a million of "How to close Excel properly" threads. But since this is a question and not an answer, I decided to ask a new one instead of asking in other people's question.</p>
  
  <p>Here's my code. But of course there's another codes in between. I'm just commenting out everything and slowly trying out which lines causes Excel to not close. I realise that even without using Garbage collector, Excel still closes. I do not want to use a sledgehammer to close Excel.</p>
  
  <p>Thanks.</p>
  
  <pre><code>Excel.Application objExcel = new Excel.Application();
  Excel.Workbooks wbs = objExcel.Workbooks;
  Excel.Workbook wb = wbs.Open(saveFileDialog1.FileName, Type.Missing,  Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
  Excel.Worksheet ws = (Excel.Worksheet)wb.ActiveSheet;
  //Excel.Range range = (Excel.Range)ws.Cells[1,1];
  Excel.Range range = ws.get_Range("A1","A1");
  
  FinalReleaseAnyComObject(range);
  FinalReleaseAnyComObject(ws);
  wb.Close(Type.Missing, Type.Missing, Type.Missing);
  FinalReleaseAnyComObject(wb);
  FinalReleaseAnyComObject(wbs);
  objExcel.Quit();
  FinalReleaseAnyComObject(objExcel);
  </code></pre>
  
  <p>Currently I've tried until objExcel, wbs, wb and ws. These 4 objects does not cause a problem.</p>
  
  <pre><code>private static void FinalReleaseAnyComObject(object o)
  {
      Marshal.FinalReleaseComObject(o);
      o = null;
  }
  </code></pre>
  
  <p>I realise that you cannot reuse the variable as well.</p>
  
  <pre><code>Excel.Range range = ws.get_Range("A1","G1");
  range = ws.get_Range("A1", "A1");
  </code></pre>
  
  <p>This will cause Excel not to close properly too. Instead, use this.</p>
  
  <pre><code>Excel.Range range = ws.get_Range("A1","G1");
  FinalReleaseAnyComObject(range);
  range = ws.get_Range("A1", "A1");
  </code></pre>