中級 › 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
空欄を埋めてビルドを通す
foreach中に要素数を変えると、反復子が不整合を検知して例外を投げます。
次の問題