473,805 Members | 2,297 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

stepping through a collection object in a foreach loop



This is very strange. Say I have code like this. I am simply looping
through a collection object in a foreach loop.

Course course = new Course();

foreach(Student s in course.Students )
{
Console.WriteLi ne(s.StudentID) ;
}

When I run the code without debugging, it runs fine. Then when I step
through the loop, I get this error.

An unhandled exception of type 'System.Invalid OperationExcept ion'
occurred in mscorlib.dll

Additional information: Collection was modified; enumeration operation
may not execute.
The implmentation of course.Students ? Very straightforward .

public ArrayList Students
{
get
{
if (students == null)
students = new ArrayList();

for(int i=0; i<5; i++)
{
Student s = new Student();
s.StudentID = i;
students.Add(s) ;
}
return students;
}
}

I want Students to be refreshed every time it's called. Now if I do
this (see below), this code will make sure that the Students gets
populated only once. That is not what I want.

What is very strange is that I've been doing this the past 3 years.
Stepped through loops about a trillion types and my implmentation has
always been like the one above.

What I have is a fresh installation of .NET. This is just strange.

public ArrayList Students
{
get
{
if (students == null)
{
students = new ArrayList();

for(int i=0; i<5; i++)
{
Student s = new Student();
s.StudentID = i;
students.Add(s) ;
}
}
return students;
}
}

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #1
5 2657
Hi David,
the reason for your error is that while you are looping throught the
Students arraylist i.e.
Course course = new Course();

foreach(Student s in course.Students )
{
Console.WriteLi ne(s.StudentID) ;
}
The Students array list was modified which is not allowed. Are you running
this code in a multithreaded environment. Something must have called
course.Students on the same instance of course while another thread was in
the foreach loop.

I would place a lock around the setting and getting of the students
arraylist to make sure it cannot be modified whilst you are looping through
it something like:

public ArrayList Students
{
get
{
if (students == null)
students = new ArrayList();

lock(students.S yncRoot)
{
for(int i=0; i<5; i++)
{
Student s = new Student();
s.StudentID = i;
students.Add(s) ;
}
}
return students;
}
}

and
Course course = new Course();

lock(course.Stu dents.SyncRoot)
{
foreach(Student s in course.Students )
{
Console.WriteLi ne(s.StudentID) ;
}
}

Hope that helps
Mark R Dawson
http://www.markdawson.org


"David C" wrote:


This is very strange. Say I have code like this. I am simply looping
through a collection object in a foreach loop.

Course course = new Course();

foreach(Student s in course.Students )
{
Console.WriteLi ne(s.StudentID) ;
}

When I run the code without debugging, it runs fine. Then when I step
through the loop, I get this error.

An unhandled exception of type 'System.Invalid OperationExcept ion'
occurred in mscorlib.dll

Additional information: Collection was modified; enumeration operation
may not execute.
The implmentation of course.Students ? Very straightforward .

public ArrayList Students
{
get
{
if (students == null)
students = new ArrayList();

for(int i=0; i<5; i++)
{
Student s = new Student();
s.StudentID = i;
students.Add(s) ;
}
return students;
}
}

I want Students to be refreshed every time it's called. Now if I do
this (see below), this code will make sure that the Students gets
populated only once. That is not what I want.

What is very strange is that I've been doing this the past 3 years.
Stepped through loops about a trillion types and my implmentation has
always been like the one above.

What I have is a fresh installation of .NET. This is just strange.

public ArrayList Students
{
get
{
if (students == null)
{
students = new ArrayList();

for(int i=0; i<5; i++)
{
Student s = new Student();
s.StudentID = i;
students.Add(s) ;
}
}
return students;
}
}

*** Sent via Developersdex http://www.developersdex.com ***

Nov 17 '05 #2

David C wrote:
This is very strange. Say I have code like this. I am simply looping
through a collection object in a foreach loop.

Course course = new Course();

foreach(Student s in course.Students )
{
Console.WriteLi ne(s.StudentID) ;
}

When I run the code without debugging, it runs fine. Then when I step
through the loop, I get this error.

An unhandled exception of type 'System.Invalid OperationExcept ion'
occurred in mscorlib.dll

Additional information: Collection was modified; enumeration operation
may not execute.
The implmentation of course.Students ? Very straightforward .

public ArrayList Students
{
get
{
if (students == null)
students = new ArrayList();

for(int i=0; i<5; i++)
{
Student s = new Student();
s.StudentID = i;
students.Add(s) ;
}
return students;
}
}

I want Students to be refreshed every time it's called. Now if I do
this (see below), this code will make sure that the Students gets
populated only once. That is not what I want.


you are not refreshing anything. every time the get accessor is
called, you add 5 more Student objects to it.

when the debugger is running, in order to display the information in
the debugger, it will invoke the get accessor and cause 5 more objects
to be added to the ArrayList, and foreach loop fails.

Nov 17 '05 #3
Hi,

You cannot modify the collection when you are iterating.

if you want to update the collection elements you would have to implement
the iterator yourself.
you could implement IEnumerator.Cur rent like:

object IEnumerator.Cur rent
{
get
{
//update the student
students[ i].Update(); //or whatever method you use
return students[ i++];
}
}


cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
"David C" <no*******@nosp am.com> wrote in message
news:ea******** ******@TK2MSFTN GP14.phx.gbl...


This is very strange. Say I have code like this. I am simply looping
through a collection object in a foreach loop.

Course course = new Course();

foreach(Student s in course.Students )
{
Console.WriteLi ne(s.StudentID) ;
}

When I run the code without debugging, it runs fine. Then when I step
through the loop, I get this error.

An unhandled exception of type 'System.Invalid OperationExcept ion'
occurred in mscorlib.dll

Additional information: Collection was modified; enumeration operation
may not execute.
The implmentation of course.Students ? Very straightforward .

public ArrayList Students
{
get
{
if (students == null)
students = new ArrayList();

for(int i=0; i<5; i++)
{
Student s = new Student();
s.StudentID = i;
students.Add(s) ;
}
return students;
}
}

I want Students to be refreshed every time it's called. Now if I do
this (see below), this code will make sure that the Students gets
populated only once. That is not what I want.

What is very strange is that I've been doing this the past 3 years.
Stepped through loops about a trillion types and my implmentation has
always been like the one above.

What I have is a fresh installation of .NET. This is just strange.

public ArrayList Students
{
get
{
if (students == null)
{
students = new ArrayList();

for(int i=0; i<5; i++)
{
Student s = new Student();
s.StudentID = i;
students.Add(s) ;
}
}
return students;
}
}

*** Sent via Developersdex http://www.developersdex.com ***

Nov 17 '05 #4
>>public ArrayList Students
{
get
{
if (students == null)
students = new ArrayList();

for(int i=0; i<5; i++)
{
Student s = new Student();
s.StudentID = i;
students.Add(s) ;
}
return students;
}
}

and also you shouldn't do things like this in a getter
Nov 17 '05 #5


Thank you all for your replies.

I had a friend run the code with his install of VS.NET 2003, and can
step through this without a problem.

So looks like there is a problem with my instance of VS.NET 2003. I
wouldn't know how to began to address that.

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1872
by: Iulian Ionescu | last post by:
I have seen the following block of code used by many people to loop through the items in a collection: IEnumerator e; IDisposable disposable1; Object obj1; e = SomeCollection.GetEnumerator(); try { while (e.MoveNext())
2
1185
by: Robert Sentgerath | last post by:
Foreach is a relative handy construct to avoid having to create the classic "for(int loop = 0; loop < collection.Length; loop++) construct. Though when I use foreach instead I do not have access to a loop variable that allows me to display a status message such as "Processing 4 out of 10". Is there a more elegant way to code the following and avoid having to declare the index variable? DirectoryInfo diImport = new...
7
2720
by: juli | last post by:
I have strings variables in a collection list and I want to create new collection but to add to it only strings that are distinct (no common strings). For example I have an object sentense which is the base for a collection and there are words in it and I want to create a new collection of sentenses where there is no similar secound word in those sentenses. How do I do this distinct selection from a collection of object? Thanks!
2
2987
by: Robert W. | last post by:
I'm trying to write a utility that will use Reflection to examine any data model I pass it and correctly map out this model into a tree structure. When I say "any" , in fact there will only be 3 types of items in the very hierarchical data model: - Classes (and nested classes) - Collections - Properties I've successfully written the Reflection code to handle any combination of classes and properties but I'm confused about what to do...
13
14501
by: TrintCSD | last post by:
How can I reset the collections within a foreach to be read as a change from within the foreach loop then restart the foreach after collections has been changed? foreach(string invoice in findListBox.listBox2.Items) { listBox2.Items count changed, restart this foreach } Thanks for any help.
25
4011
by: David C | last post by:
I posted this question, and from the replies, I get the impression that I worded my posting very poorly, so let me try this again. While debugging and stepping through this foreach loop foreach(Student s in course.Students) { Console.WriteLine(s.StudentID); }
4
15027
by: John Dalberg | last post by:
I am looking at a problem which is preventing my code to get a reference to any asp control inside a div section which has a runat=server attribute. This can be reproduced in a simple test: Create a blank webform and add this html inside the <formsection: <div id="myDiv" runat=server> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </div> In the code behind, add this code in the page_load event handler:
0
1509
by: Geoffrey | last post by:
Hello, I work with .net remoting,to simplify, when the client connected, he send an handle to an object, the object is used to exchange message and events. no problem. In my server, I keep a list of all actives clients and the handle of each., no problem In remoting, it's difficult to see when a client is disconnected, so I use asynchronous call to contact the client and if I got an error when I call EndInvoke =the client is...
3
2294
by: gasfusion | last post by:
Hey guys. I'm building an object collection which will be a part of a Data Access Layer i am currently working on. However, i am having some issues iterating through a collection. This is what i've done so far 1 - Create 'user' class which maps to the MySQL table. The class has basic setters and getters to set/get each field value. 2 - Created a collection class with simple add/remove/get methods. 3 - Created user collection class which...
0
9596
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10617
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10370
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10109
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7649
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6876
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5545
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4328
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3849
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.