Code Fix

中級 › Collection was modified の原因と直し方 › パターン4

Collection was modified の原因と直し方

foreach中にList等のコレクションの要素数を変えると発生します。

 1  class Program {
 2      static void Main(string[] args) {
 3          var vals = new System.Collections.Generic.List<int> { 5, 10, 15 };
 4          foreach (int v in vals) {
 5              if (v == 10) {
 6                  ___________________________;
                                 ^
 7              }
 8          }
 9      }
10  }
Unhandled exception. System.InvalidOperationException: Collection was modified; enumeration operation may not execute. at Program.Main(String[] args) in Program.cs:line 4

空欄を埋めてビルドを通す

広告
広告スロット(未設定)

Collection was modified の原因と直し方

反復子(イテレータ)が内部状態の不整合を検知する仕組みです。

このエラーの解説と類題をまとめて見る →

広告
広告スロット(未設定)