Practice mode C#

What happens if you call list.Remove(item) on a List inside a foreach loop over that same list?

Correct answer C. An InvalidOperationException is thrown when the loop continues

Explanation

A List enumerator records the list's version. Adding or removing items changes it, and the next MoveNext call detects this and throws InvalidOperationException saying the collection was modified. The compiler cannot detect this. To remove items safely, loop backwards with a for statement, use list.RemoveAll(predicate), or iterate over a copy.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.