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!

 

 



  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

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

# re: Collection was modified after the enumerator was instantiated

Nice job 12/2/2009 6:58 PM | Dennis

# re: Collection was modified after the enumerator was instantiated

Cheers for that. Saved me hours of translation time.
My only thought is are you like me using the code in the aspx page between <% %> rather than in code behind?
2/28/2011 12:00 PM | Darren

Post a comment