System.InvalidOperationException
An InvalidOperationException is thrown when a method call is not valid for the current state of an object. The arguments can be fine, but the object is not ready for the call, or the data it works on does not fit the operation.
It is one of the most common exceptions in .NET, because the framework and many libraries use it for any state problem. The message is the part that tells you what went wrong, such as Sequence contains no elements or Collection was modified.
Minimum version: >= 1.1 >= Core 1.0
Statistics
Common causes
The message identifies which of these it is. These are the cases that show up the most.
A LINQ method that finds nothing
First, Single, Last and Max throw when the sequence is empty, or when no element matches. Single also throws when more than one element matches.
var orders = new List<Order>();
var first = orders.First(); // InvalidOperationException: Sequence contains no elements
Use the OrDefault variant, and handle the case where nothing was found:
var orders = new List<Order>();
var first = orders.FirstOrDefault();
if (first is null)
{
Console.WriteLine("No orders yet.");
}
A collection that is changed while you loop over it
Adding to or removing from a list inside a foreach invalidates the enumerator, and the next step of the loop throws Collection was modified; enumeration operation may not execute.
var items = new List<string> { "a", "b", "c" };
foreach (var item in items)
{
if (item == "b") items.Remove(item); // InvalidOperationException on the next iteration
}
Remove with RemoveAll, or loop over a copy of the list:
var items = new List<string> { "a", "b", "c" };
items.RemoveAll(item => item == "b");
foreach (var item in items.ToList())
{
items.Remove(item);
}
A nullable value without a value
Reading .Value on a nullable that is null throws Nullable object must have a value. It is a different exception from the NullReferenceException, since a nullable value type is not a reference.
int? quantity = null;
var value = quantity.Value; // InvalidOperationException
Use a default value, or check HasValue first:
int? quantity = null;
var value = quantity ?? 1;
if (quantity.HasValue)
{
Console.WriteLine(quantity.Value);
}
A service that dependency injection cannot create
In ASP.NET Core, Unable to resolve service for type means that a class asks for a service that was never registered. Cannot consume scoped service from singleton means that the lifetimes do not match, and shows up when the application starts.
Register the service with the lifetime it needs. A singleton cannot depend on a scoped service, so make the consumer scoped as well, or create a scope when you need the service:
builder.Services.AddScoped<IOrderService, OrderService>();
How to fix it and prevent it
Prefer methods that do not throw
Many APIs have a variant that reports failure with a return value instead: FirstOrDefault, TryGetValue, TryParse and GetValueOrDefault. Use them when a missing value is a normal case.
var numbers = new List<int>();
var largest = numbers.DefaultIfEmpty().Max();
Change a copy, not the collection you loop over
Create the copy with ToList() before the loop, or collect the changes and apply them after. For code that runs on several threads, use the collections in System.Collections.Concurrent.
Check the state before the call
If you own the class, validate the state at the top of the method and throw with a message that says what the caller did wrong. Do not leave it to a line further down.
private bool _opened;
public void Send(string message)
{
if (!_opened)
{
throw new InvalidOperationException("Call Open before Send.");
}
}
How to read the stack trace
The message is the best clue, and the first frame in your own code is the call that was not valid:
System.InvalidOperationException: Sequence contains no matching element
at System.Linq.ThrowHelper.ThrowNoMatchException()
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate)
at Shop.Services.OrderLookup.Find(Int32 id) in C:\src\Shop\Services\OrderLookup.cs:line 14
at Program.<Main>$(String[] args) in C:\src\Shop\Program.cs:line 4
The message says that First found no matching element, and the call is on line 14 of OrderLookup.cs. The two lines at the top are from LINQ, so the cause is in the data that was passed in. Find out why no customer with that id exists.
Should you catch it?
Usually not. This exception reports that the code is wrong or the data is not what you expected, so the fix is to change the code. A catch hides the problem.
Catch it only where it comes from outside of your control, such as a library that throws it for a state you cannot check first. Keep the try block small, so you know which call threw.
Find InvalidOperationException before your users do
elmah.io logs every unhandled exception in your .NET application with its stack trace and request details, groups identical errors and notifies you when a new one appears.
Start free trialRelated exceptions
- ObjectDisposedException is a derived class, thrown when you use an object that has been disposed.
- NotSupportedException is thrown when an operation can never work on that type.
- NullReferenceException is thrown when you use a reference that is null.
Frequently asked questions
What is the difference between First and FirstOrDefault?
First throws an InvalidOperationException when nothing is found. FirstOrDefault returns null, or the default value of the type, so you must check the result.
Why does Single throw when there are two matches?
Single promises that there is exactly one. If there are none or more than one, it throws. Use First if you only need one of them.
What does "Collection was modified" mean?
You changed a collection while a loop was reading it. Loop over a copy, or use RemoveAll. Another thread that changes the collection gives the same exception.
What is the difference from ArgumentException?
An ArgumentException says that an argument is wrong. An InvalidOperationException says that the call is wrong for the current state, even if the arguments are fine.
Let your AI agent track it down
Connect Claude Code, Cursor, VS Code or Visual Studio to the elmah.io MCP server and ask your agent to look into InvalidOperationException for you. For example:
The agent reads the stack trace and request details from elmah.io, finds the code in your repository and proposes a fix. In Claude Code, add the server with one command:
claude mcp add --transport http --client-id claudecode elmahio https://mcp.elmah.io/mcp
The MCP server is included on every plan and is currently in beta. Set up the MCP server.
Further reading
YouTube videos
Answers from Stack Overflow
Here's a workaround I found that works for all cases (including suspended dispatchers). It's not my code and I'm still working to fully understand it, but it does work.
It can be called using:
customerList = AsyncHelpers.RunSync<List<Customer>>(() => GetCustomers());
Code is from here
public static class AsyncHelpers
{
/// <summary>
/// Synchronously execute's an async Task method which has a void return value.
/// </summary>
/// <param name="task">The Task method to execute.</param>
public static void RunSync(Func<Task> task)
{
var oldContext = SynchronizationContext.Current;
var syncContext = new ExclusiveSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(syncContext);
syncContext.Post(async _ =>
{
try
{
await task();
}
catch (Exception e)
{
syncContext.InnerException = e;
throw;
}
finally
{
syncContext.EndMessageLoop();
}
}, null);
syncContext.BeginMessageLoop();
SynchronizationContext.SetSynchronizationContext(oldContext);
}
/// <summary>
/// Synchronously execute's an async Task<T> method which has a T return type.
/// </summary>
/// <typeparam name="T">Return Type</typeparam>
/// <param name="task">The Task<T> method to execute.</param>
/// <returns>The result of awaiting the given Task<T>.</returns>
public static T RunSync<T>(Func<Task<T>> task)
{
var oldContext = SynchronizationContext.Current;
var syncContext = new ExclusiveSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(syncContext);
T result;
syncContext.Post(async _ =>
{
try
{
result = await task();
}
catch (Exception e)
{
syncContext.InnerException = e;
throw;
}
finally
{
syncContext.EndMessageLoop();
}
}, null);
syncContext.BeginMessageLoop();
SynchronizationContext.SetSynchronizationContext(oldContext);
return result;
}
private class ExclusiveSynchronizationContext : SynchronizationContext
{
private readonly AutoResetEvent workItemsWaiting = new AutoResetEvent(false);
private readonly Queue<Tuple<SendOrPostCallback, object>> items =
new Queue<Tuple<SendOrPostCallback, object>>();
private bool done;
public Exception InnerException { get; set; }
public override void Send(SendOrPostCallback d, object state)
{
throw new NotSupportedException("We cannot send to our same thread");
}
public override void Post(SendOrPostCallback d, object state)
{
lock (items)
{
items.Enqueue(Tuple.Create(d, state));
}
workItemsWaiting.Set();
}
public void EndMessageLoop()
{
Post(_ => done = true, null);
}
public void BeginMessageLoop()
{
while (!done)
{
Tuple<SendOrPostCallback, object> task = null;
lock (items)
{
if (items.Count > 0)
{
task = items.Dequeue();
}
}
if (task != null)
{
task.Item1(task.Item2);
if (InnerException != null) // the method threw an exeption
{
throw new AggregateException("AsyncHelpers.Run method threw an exception.", InnerException);
}
}
else
{
workItemsWaiting.WaitOne();
}
}
}
public override SynchronizationContext CreateCopy()
{
return this;
}
}
}
By Rachel. Read the original answer on Stack Overflow.
ILogger is no longer registered by default but ILogger<T> is. If you still want to use ILogger you can register it manually with the following (in Startup.cs):
public void ConfigureServices(IServiceCollection services)
{
var serviceProvider = services.BuildServiceProvider();
var logger = serviceProvider.GetService<ILogger<AnyClass>>();
services.AddSingleton(typeof(ILogger), logger);
...
}
Where AnyClass can be something generic, such as:
public class ApplicationLogs
{
}
So:
public void ConfigureServices(IServiceCollection services)
{
var serviceProvider = services.BuildServiceProvider();
var logger = serviceProvider.GetService<ILogger<ApplicationLog>>();
services.AddSingleton(typeof(ILogger), logger);
...
}
ILogger will now resolve via constructor injection.
By Sam Shiles. Read the original answer on Stack Overflow.
To revert the last applied migration you should:
- Revert migration from database:
PM> Update-Database <prior-migration-name>PS/cmd> dotnet ef database update <prior-migration-name>
- If you call
dbContext.Database.Migrate()/MigrateAsync()inMain/Startup: remove the latest migration file from project (or it will be reapplied again on next step) - Update model snapshot:
PM> Remove-MigrationPS/cmd> dotnet ef migrations remove
By Dmitry Polomoshnov. Read the original answer on Stack Overflow.
You should delete migration '20160703192724_MyFirstMigration' record from '_EFMigrationsHistory' table.
otherwise below command will remove migration and delete migrations folder:
PMC Command:
> remove-migration -force
CLI Command:
> dotnet ef migrations remove -f
By Amin Golmahalleh. Read the original answer on Stack Overflow.
Simply you can target a Migration by value
Update-Database -Migration:0
Then go ahead and remove it
Remove-Migration
NOTE this is for when you want to clear database.
By John Nyingi. Read the original answer on Stack Overflow.
Source: Stack Overflow