Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Short answer: This is not safe.</p> <p>Long answer: From the <a href="http://msdn.microsoft.com/en-us/library/78dfe2yb.aspx" rel="nofollow noreferrer"><code>IEnumerator&lt;T&gt;</code> documentation</a>:</p> <blockquote> <p>An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined.</p> </blockquote> <p>Note that the docs say the behavior is undefined, which means that it might work and it might not. One should never rely on undefined behavior.</p> <p>In this case, it depends on the behavior of the <code>Keys</code> enumerable, regarding whether or not it creates a copy of the list of keys when you begin enumerating. In this specific case, we know from <a href="http://msdn.microsoft.com/en-us/library/yt2fy5zk.aspx" rel="nofollow noreferrer">the docs</a> that the return value from <code>Dictionary&lt;,&gt;.Keys</code> is a collection that refers back to the dictionary:</p> <blockquote> <p>The returned <code>Dictionary&lt;TKey, TValue&gt;.KeyCollection</code> is not a static copy; instead, the <code>Dictionary&lt;TKey, TValue&gt;.KeyCollection</code> refers back to the keys in the original <code>Dictionary&lt;TKey, TValue&gt;</code>. Therefore, changes to the <code>Dictionary&lt;TKey, TValue&gt;</code> continue to be reflected in the <code>Dictionary&lt;TKey, TValue&gt;.KeyCollection</code>.</p> </blockquote> <p>So it should be considered unsafe to modify the dictionary while enumerating the dictionary's keys.</p> <p>You can correct this with one change. Alter this line:</p> <pre><code>foreach (string dir in sourceDirInclusion.Keys) </code></pre> <p>To this:</p> <pre><code>foreach (string dir in sourceDirInclusion.Keys.ToList()) </code></pre> <p>The <code>ToList()</code> extension method will create an explicit copy of the list of keys, making it safe to modify the dictionary; the "underlying collection" will be the copy and not the original.</p>
    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.
    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