2
votes

To avoid the error "Collection was modified after the enumerator was instantiated" I found a number of recommendations to use the following lines before looping through the Request.ServerVariables.Keys collection:

IEnumerator en = Request.ServerVariables.Keys.GetEnumerator();
en.MoveNext();

Looking at the MSDN example, they set the Server Variables to a collection, then iterate through that collection without calling GetEnumerator or MoveNext.

Two questions:

  1. Why do we need to call GetEnumerator and MoveNext?
  2. Which is the better approach if using ASP.NET and C# 4.0?
3

3 Answers

6
votes

You can also use:

 string[] keys = Request.ServerVariables.AllKeys;
 foreach(string key in keys )
 {
      if(Request.ServerVariables[key] != null)
      {
           string value = Request.ServerVariables[key];
      }
 }
3
votes

What you can do is to create a new collection from the server variables:

foreach(var key in Request.ServerVariables.AllKeys.ToList())
{
    var value = Request.ServerVariables[key];
    ...
}

ToList() extension method will create a new List with the items. If you change the ServerVariables collection you won't be changing the collection you are iterating (as it's a new one).

Hope it helps.

EDIT

Just answering your questions: 1- Those methods are for iterating the collection. Is the framework way of managing the iteration. If you can iterate, you can use foreach. 2- The best way is to use a foreach, as it's more readable than working with enumerables.

0
votes

You can get the "Collection was modified after the enumerator was instantiated." error, when you set EnableViewState="False" for controls that post back data.