If you’re learning C# and have encountered the InvalidOperationException
, don’t worry — it’s one of the most common runtime errors. This exception occurs when an action is invalid given the object’s current state.
For example, trying to use an enumerator that’s already been disposed or modifying a collection during iteration can trigger it.
Let’s walk through how and why it happens, and most importantly, how to fix it.
What Causes This Error?
1. Modifying a collection while iterating
foreach (var item in myList)
{
myList.Remove(item); // Causes InvalidOperationException
}
You can’t modify a collection (e.g., add or remove items) during a foreach
loop.
2. Using enumerators incorrectly
IEnumerator enumerator = myList.GetEnumerator();
enumerator.MoveNext();
enumerator.Reset();
enumerator.MoveNext();
In some contexts, calling Reset()
or accessing elements after disposing of the enumerator can cause issues.
3. Multiple operations on closed resources
Using objects like data readers or file streams after they’ve been closed or disposed can lead to InvalidOperationException
.
4. Wrong sequence of method calls
For example, calling Read()
before opening a connection, or using Start()
on a thread that has already been started.
How to Fix It
Fix 1: Use a separate list when modifying during iteration
var itemsToRemove = myList.Where(item => ShouldRemove(item)).ToList();
foreach (var item in itemsToRemove)
{
myList.Remove(item);
}
This avoids modifying the collection while iterating.
Fix 2: Check object state before performing operations
if (reader != null && !reader.IsClosed)
{
reader.Close();
}
This ensures the object is in the correct state before you act on it.
Fix 3: Use for
loops instead of foreach
when modifying collections
for (int i = myList.Count - 1; i >= 0; i--)
{
if (ShouldRemove(myList[i]))
{
myList.RemoveAt(i);
}
}
This gives you control over the index and avoids iterator-related issues.
Real Example
Problem Code
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
foreach (var name in names)
{
if (name.StartsWith("A"))
{
names.Remove(name); // Triggers InvalidOperationException
}
}
Fixed Version
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
var namesToRemove = names.Where(name => name.StartsWith("A")).ToList();
foreach (var name in namesToRemove)
{
names.Remove(name);
}
Tips to Prevent This Error
- Avoid modifying collections in
foreach
loops. Usefor
loops or temporary lists. - Always check object state (e.g., not null, not disposed) before operations.
- Use try-catch around code that could trigger this exception to handle it gracefully.
Conclusion
The InvalidOperationException
is common but manageable once you understand how it works.
By checking object states and managing collections properly, you can prevent this error from disrupting your code.
Bookmark this page or keep a note for future debugging!