Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7950457
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T02:16:41+00:00 2026-06-04T02:16:41+00:00

Given the following code, I’m curious to know how to avoid the following exception

  • 0

Given the following code, I’m curious to know how to avoid the following exception

System.InvalidOperationException was unhandled
Message=Collection was modified; enumeration operation may not execute.
Source=mscorlib
StackTrace:
   at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
   at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
   at System.Collections.Generic.List`1.Enumerator.MoveNext()
   at PBV.Program.Main(String[] args) in C:\Documents and Settings\tmohojft\Local Settings\Application Data\Temporary Projects\PBV\Program.cs:line 39
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()
InnerException: 

CODE:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PBV
{
class Program
{
    struct structItem
    {
        public int y { get; set; }
        public int z { get; set; }
    }

    struct testStruct
    {
        public int x { get; set; }
        public List<structItem> items { get; set; }
    }

    static void Main(string[] args)
    {
        testStruct a = new testStruct();
        structItem b = new structItem();

        for (byte i = 0; i <= 10; i++) {
            b.y = i;
            b.z = i * 2;
            a.items = new List<structItem>();
            a.items.Add(b);
        }

        testStruct c = new testStruct();
        c = a;

        int counter = 0;

        //exception thrown on line below
        foreach (var item in a.items) {
            structItem d = item;
            d.z = 3;

            c.items[counter] = d;
            counter++;
        }

        a = c;
    }
}
}

I originally tried to simply put the following in the second foreach:

item.z = 3;

But that caused the following error:

Cannot modify members of "item" because it is a "foreach iteration" 

I tried to create a temporary object in order to be able to modify the struct data inside the foreach, but I recieve the exception above. My best guess is because my temporary struct is saving a reference to the original struct rather than the value itself – which is leading my original struct to be updated when my temporary struct is.

So my question is:
How do I pass this struct by value rather than reference? Or is there an entirely different way to get around this issue?

Thanks in advance for the help.

EDIT: Thanks for all the answers guys. I’m aware that the list is a reference type, but does that make it impossible to pass by value instead of reference then?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T02:16:44+00:00Added an answer on June 4, 2026 at 2:16 am

    I’m a little confused by what your example code is trying to do, but I think perhaps part of your confusion may be that when you set c = a, you expect it to make a copy of the list. It does not. While the structure itself is a value type, the items property it contains is not. List<> is a reference type, so when you set c = a, it copies that items reference to c. So, when you enter the loop, both a and c contain a reference to the same list object. Therefore, when you modify the list while you are enumerating through it, it will always fail.

    A simple way to avoid this is to iterate through a static copy of your list:

    foreach (var item in a.items.ToArray())
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Given the following code from a Microsoft example: public class EngineMeasurementCollection : Collection<EngineMeasurement> {
Given the following code: using System.Collections.Generic; static class Program { static void Main() {
Given the following code snippet below, using GetPropValue(MyComponent,'MySubComponent.Prop1') raises an EPropertyError exception. How can
Given the following code: interface IParam {} class Parameter implements IParam {} void foo(Collection<?
Given the following code, I would expect to an empty result or an exception:
Given the following code, is there a way I can call class A's version
Given the following code $c= new SoapClient('http://www.webservicex.net/CurrencyConvertor.asmx?WSDL'); $usa = USD; $eng = GBP; doing
Given the Following Code how Would i Change/Set my Silverlight WCF Service URI in
Given the following code: int *a = NULL; a = calloc(1, sizeof(*a)); printf(%d\n, a);
Given the following code (it's supposed to write helloworld in a helloworld file, and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.