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

  • SEARCH
  • Home
  • 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 9209049
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T00:45:04+00:00 2026-06-18T00:45:04+00:00

I know that in .net collection types (or at least some collection types) do

  • 0

I know that in .net collection types (or at least some collection types) do not allow modify the collection when you are iterating on it.

For example in the List class exist a code like this:

if (this.version != this.list._version)
 ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);

But obviously this is a decision of the developers that design the iterator class, because I can provide some implementations of IEnumerable that at least do not throw any Exception when the under-laying collection is modified.

Then I have some questions:

  • Why I should not modify a collection when I am iterating on it ?

  • It is possible to create a collection that support to be modified when iterating on it, without to have any other problems ? (NOTE: that the first answer can answer this one too)

  • When the C# compiler generate the Enumerator interface implementation takes into account this such of things?

  • 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-18T00:45:05+00:00Added an answer on June 18, 2026 at 12:45 am

    Why I should not modify a collection when I am iterating on it?

    Some collections can be modified when iterating, so it’s not globally bad. In most cases it’s very difficult to write an effective iterator that will work correctly even when the underlying collection is modified. In many cases the exception is the iterator writer punting and saying that they just don’t want to deal with it.

    In certain cases it’s not clear what the iterator should do when the underlying collection is changed. Some cases are clear-cut, but for others different people will expect different behavior. Whenever you’re in that situation it’s a sign that there is a deeper problem (that you shouldn’t mutating a sequence that you’re iterating)

    It is possible to create a collection that support to be modified when iterating on it, without to have any other problems ? (NOTE: that the first answer can answer this one too)

    Sure.

    Consider this iterator for a list:

    public static IEnumerable<T> IterateWhileMutating<T>(this IList<T> list)
    {
        for (int i = 0; i < list.Count; i++)
        {
            yield return list[i];
        }
    }
    

    If you remove an item at or before the current index from the underlying list then an item will be skipped while iterating. If you add an item at or before the current index the an item will be duplicated. But if you add/remove items past the current index during iteration then there won’t be a problem. We could try to be fancy and make an attempt to see if an item was removed/added from the list and adjust the index accordingly, but it couldn’t always work, so we wouldn’t be able to handle all cases. If we had something like an ObservableCollection then we could be notified of additions/removals and their indexes and adjust the index accordingly, thus allowing the iterator to handle mutatings of the underlying collection (as long as it’s not in another thread).

    Since an iterator for an ObservableCollection can know both when any items are added/removed, and where they are, it can adjust it’s position accordingly. I am unsure if the built in iterator properly handles mutation, but here is one that will handle any mutation of the underlying collection:

    public static IEnumerable<T> IterateWhileMutating<T>(
        this ObservableCollection<T> list)
    {
        int i = 0;
        NotifyCollectionChangedEventHandler handler = (_, args) =>
        {
            switch (args.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    if (args.NewStartingIndex <= i)
                        i++;
                    break;
                case NotifyCollectionChangedAction.Move:
                    if (args.NewStartingIndex <= i)
                        i++;
                    if (args.OldStartingIndex <= i) //note *not* else if
                        i--;
                    break;
                case NotifyCollectionChangedAction.Remove:
                    if (args.OldStartingIndex <= i)
                        i--;
                    break;
                case NotifyCollectionChangedAction.Reset:
                    i = int.MaxValue;//end the sequence
                    break;
                default:
                    //do nothing
                    break;
            }
        };
        try
        {
            list.CollectionChanged += handler;
            for (i = 0; i < list.Count; i++)
            {
                yield return list[i];
            }
        }
        finally
        {
            list.CollectionChanged -= handler;
        }
    }
    
    • If an item is removed from “earlier” in the sequence, we continue normally without skipping an item.

    • If an item is added “earlier” in the sequence we won’t show it, but we also won’t show some other item twice.

    • If an item is moved from before the current position to after it will be shown twice, but no other item will be skipped or repeated. If an item is moved from after the current position to before the current position it won’t be shown, but that’s all. If an item is moved from either later in the collection to another spot later, there is no problem, and the move will be seen in the result, if it is moved from an earlier spot to another earlier spot, everything is fine and the move won’t be “seen” by the iterator.

    • Replacing an item isn’t a problem; it will only be seen if it’s “after” the current position though.

    • Resetting the collection results in the sequence ending gracefully at the current position.

    Note that this iterator won’t handle situations with multiple threads. If another thread mutates the collection while another is iterating, bad things could happen (items being skipped or repeated, or even exceptions, such as index out of bounds exceptions). What this does allow is mutations during iteration in which there is either only one thread, or in which only one thread is ever executing code that moves the iterator or mutates the collection.

    When the C# compiler generate the Enumerator interface implementation takes into account this such of things?

    The compiler doesn’t generate the interface implementation; a person does.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i know that .NET String class uses such behaviour, but I can't find any
Certain collection types in .Net have an optional Initial Capacity constructor parameter. For example:
Some ASP.NET controls only permit items of certain types, for example: <uc:MyControl runat=server....> <MyTableTemplate>
I know that .NET assembly is self-descriptive because of the metadata. Now suppose I
I know that ASP.NET MVC 1.0 is bin-deployable as explained in Phil Haack's article.
i know that in vb.net you can just do Exit Sub but i would
I know that the static objects in .Net managed world are loaded in Loader
I know that the reason that Microsoft came out with ASP.NET MVC was to
We know that behind the scenes, the ASP.NET MVC framework will use reflection to
Occasionally I will know that there is a .NET Framework function that returns a

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.