
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Handle Collection Modified Error in C#
This error occurs when a looping process is being running on a collection (Ex: List) and the collection is modified (data added or removed) during the runtime.
Example
using System; using System.Collections.Generic; namespace DemoApplication { public class Program { static void Main(string[] args) { try { var studentsList = new List<Student> { new Student { Id = 1, Name = "John" }, new Student { Id = 0, Name = "Jack" }, new Student { Id = 2, Name = "Jack" } }; foreach (var student in studentsList) { if (student.Id <= 0) { studentsList.Remove(student); } else { Console.WriteLine($"Id: {student.Id}, Name: {student.Name}"); } } } catch(Exception ex) { Console.WriteLine($"Exception: {ex.Message}"); Console.ReadLine(); } } } public class Student { public int Id { get; set; } public string Name { get; set; } } }
Output
The output of the above code is
Id: 1, Name: John Exception: Collection was modified; enumeration operation may not execute.
In the above example, the foreach loop is executed on the studentsList. When the Id of the student is 0, the item will be removed from the studentsList. Because of this change the studentsList gets modified (resized) and an exception is being thrown during the runtime.
Fix for the above issue
To overcome the above issue, perform a ToList() operation on the studentsList before the start of each iteration.
foreach (var student in studentsList.ToList())
Example
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace DemoApplication { public class Program { static void Main(string[] args) { var studentsList = new List<Student> { new Student { Id = 1, Name = "John" }, new Student { Id = 0, Name = "Jack" }, new Student { Id = 2, Name = "Jack" } }; foreach (var student in studentsList.ToList()) { if (student.Id <= 0) { studentsList.Remove(student); } else { Console.WriteLine($"Id: {student.Id}, Name: {student.Name}"); } } Console.ReadLine(); } } public class Student { public int Id { get; set; } public string Name { get; set; } } }
The output of the above code is
Output
Id: 1, Name: John Id: 2, Name: Jack
Advertisements