none
List<T>.ForEach in .Net 4.5 RRS feed

  • Question

  • I came across below from Microsoft site.

    The enumerator throws an InvalidOperationException exception if an element in the collection is modified.

    But this statement is not true for .net 4.5.  I am able to modify an element in the collection.

    var checkboxlist = new List<CheckBox> { CheckPatientResult, CheckLqcResult, CheckAnalyzerFaultLog, CheckDmaLog };
                if (checkBox.IsChecked == true)
                {
                    checkboxlist.ForEach(x => x.IsChecked = true); 
                }

    The above piece of code works fine in .net 4.5.2

    So I am confused what Microsoft is trying to say?

    Thursday, March 10, 2016 1:12 PM

Answers

  • I believe the paragraph is actually this:

    An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and the next call to MoveNext or Reset throws an InvalidOperationException.

    This means that its the collection itself that must remain unmodified. When it says "modify elements" it really means changing the element completely for a new or different one. E.g

    foreach(SomeClass c in MyList)
    {
       MyList[1] = new SomeClass(); // InvalidOperationException
    }

    Similarly trying to remove or add elements while enumerating will throw an exception.

    Just modifying an inner property of an element is fine.


    Thursday, March 10, 2016 1:23 PM