Chris Ongsuco's Weblog
Information Technology, business, life, food...

Collection was modified after the enumerator was instantiated

Thursday, January 26, 2006 2:21 AM
Untitled Page

Something is not right with this code:

 

foreach (string key in Request.ServerVariables.Keys)

Response.Write(string.Format("<b>{0}</b>: {1}<br>", key,

Request.ServerVariables[key]));

 

 

An error occurred saying:

Collection was modified after the enumerator was instantiated.

 

 

And so I tried:

 

for (int i = 0; i < Request.ServerVariables.Keys.Count; i++)

{

string key = Request.ServerVariables.Keys[i];

 

Response.Write(string.Format("<b>{0}</b>: {1}<br>", key,

Request.ServerVariables[key]));

}

 

Again, I tried a couple of things with the first code snippet:

 

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

en.MoveNext();

 

foreach (string key in Request.ServerVariables.Keys)

Response.Write(string.Format("<b>{0}</b>: {1}<br>", key,

Request.ServerVariables[key]));

 

 

 

Whoooaaaa! it worked!  And that’s .Net 2005 for you baby!

 

 


Feedback

# re: Collection was modified after the enumerator was instantiated

wow, thanks! is there some reason why it works with that? 8/14/2007 3:33 PM | mizzo

# re: Collection was modified after the enumerator was instantiated

WTF YOU EXPLAINED? 4/25/2008 5:17 PM | ss

# re: Collection was modified after the enumerator was instantiated

Thanks dude! just the answer I was looking for. I have no idea why it works though. 9/8/2009 4:01 AM | David Good

Post a comment