Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Because you expect a heterogeneous collection, it's better to avoid throwing <code>InvalidCastException</code> in the first place. Read up on "boneheaded exceptions" in Eric Lippert's excellent <a href="http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx" rel="nofollow">Vexing exceptions</a> article.</p> <p><strong>Option 1:</strong> Use the LINQ <a href="http://msdn.microsoft.com/en-us/library/bb360913.aspx" rel="nofollow"><code>OfType&lt;TResult&gt;()</code></a> extension method to pick out only elements of a specified type:</p> <pre><code>// using System.Linq; foreach(string myObject in myObjects.OfType&lt;string&gt;()) { sw.WriteLine(myObject); } </code></pre> <p><strong>Option 2:</strong> Do the type check yourself:</p> <pre><code>foreach(object myObject in myObjects) { string s = myObject as string; if (s != null) sw.WriteLine(s); } </code></pre> <p>This option is easy to extend to handle multiple types.</p> <p><strong>UPDATE:</strong></p> <blockquote> <p>Ok, but what would happen if, in some outlandish scenario, an exception was still thrown on this line. Is there a way to handle the exception and then continue with my enumeration?</p> </blockquote> <p>Here are the other ways an exception could be thrown on the <code>foreach</code> line, none of which you can sensibly handle:</p> <ul> <li><code>myObjects.GetEnumerator()</code> throws an exception. In this case, the enumeration can't be started at all.</li> <li><code>IEnumerator&lt;string&gt;.MoveNext()</code> throws an exception. In this case, the enumerator is likely to be corrupt, and enumeration cannot continue.</li> <li>Some other type of fatal exception occurs: <code>OutOfMemoryException</code>, <code>StackOverflowException</code>, etc. In this case, you should just let the process die.</li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload