title: Handling Casting exceptions in a foreach statement
body: <p>Ok, lets say I have an array of objects in C# .Net like so:</p>
  
  <pre><code>object[] myObjects = new object[9];
  myObjects[0] = "Foo";
  myObjects[1] = 3;
  myObjects[2] = 2.75;
  myObjects[3] = "Bar";
  myObjects[4] = 675;
  myObjects[5] = "FooBar";
  myObjects[6] = 12;
  myObjects[7] = 11;
  myObjects[8] = "FooBarFooBar";
  </code></pre>
  
  <p>I want to, inside a foreach block, enumerate this array and write every string to a text document using StreamWriter like so:</p>
  
  <pre><code>StreamWriter sw = new StreamWriter(@"C:\z\foobar.txt");
  
  foreach(string myObject in myObjects)
  {
      sw.WriteLine(myObject);
  }
  
  sw.Flush();
  sw.Close();
  </code></pre>
  
  <p>My problem is that whenever I try to cast the <code>integers</code> and <code>doubles</code> to <code>String</code>, an exception will be thrown.</p>
  
  <p>If I put a <code>try/catch</code> block around my <code>foreach</code> statement, the exception that gets thrown on the second iteration will trigger the catching of the exception and nothing will get written to my text document.</p>
  
  <p>Putting the try/catch inside the foreach is pointless because the exception happens on the cast.</p>
  
  <p>I want to use a foreach loop (let's assume that for loops don't exist, and that we can't use indexing or <code>ToString()</code>) to enumerate an array of objects, casting each to a string and writing these to a text document using <code>StreamWriter</code>. If the cast works, happy days. If not, I want to catch the exception thrown and continue to enumerate the remaining objects.</p>
  
  <p>Thanks</p>
  
  <p><strong>Edit:</strong> Before somebody says it, this isn't homework! I am trying to solve a real world problem.</p>