Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I understand it's <code>MoveNext</code> that throws the exception. </p> <p>I tried to write a method that safe-walks a sequence and tries to ignore <code>MoveNext</code> exceptions. However I'm not sure if <code>MoveNext</code> advances position when it throws an exception, so this might as well be infinite loop. It is also bad idea because we would rely on implementation details.</p> <p>But it's just <strong>so much fun!</strong></p> <pre><code>public static IEnumerable&lt;T&gt; SafeWalk&lt;T&gt; (this IEnumerable&lt;T&gt; source) { var enumerator = source.GetEnumerator(); bool? hasCurrent = null; do { try { hasCurrent = enumerator.MoveNext(); } catch { hasCurrent = null; // we're not sure } if (hasCurrent ?? false) // if not sure, do not return value yield return enumerator.Current; } while (hasCurrent ?? true); // if not sure, continue walking } foreach (var file in Directory.EnumerateFiles("c:\\", "*", SearchOption.AllDirectories) .SafeWalk()) { // ... } </code></pre> <p>This will only work if the following conditions are true about framework's implementation of this iterator (see <code>FileSystemEnumerableIterator&lt;TSource&gt;</code> in Reflector for reference):</p> <ul> <li><code>MoveNext</code> advances its position when it fails;</li> <li>When <code>MoveNext</code> fails on last element, subsequent calls will return <code>false</code> instead of throwing an exception;</li> <li>This behavior is consistent for different versions of .NET Framework;</li> <li>I haven't made any logic or syntax mistakes.</li> </ul> <p>Even if it works, please, never use it in production!<br> But I really wonder if it does.</p>
 

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