C# Reference ยท Exceptions and Diagnostics
InvalidOperationException
Reference for InvalidOperationException in C#: object-state errors, collection modified during enumeration, empty sequences with LINQ, and when to throw it yourself.
InvalidOperationException means that a method call is not valid for the current state of the object, even though the arguments themselves may be fine. It is the standard exception for state problems: reading from a closed reader, calling Dequeue() on an empty queue, or modifying a list while a foreach loop is walking it.
You meet it constantly when using the framework, and you should throw it from your own code when a method is called at the wrong time. For a bad argument value, use an ArgumentException instead.
if (!isConnected) { throw new InvalidOperationException("Connect before sending."); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public class InvalidOperationException : SystemException { public InvalidOperationException(); public InvalidOperationException(string? message); public InvalidOperationException(string? message, Exception? innerException); }
| Name | Description |
|---|---|
message |
What is wrong with the object's state and, ideally, what to do about it. |
innerException |
Optional original cause. |
ObjectDisposedException and NotSupportedException are related but separate types; ObjectDisposedException derives from InvalidOperationException.
Usage notes
- Typical sources:
Queue<T>.DequeueandStack<T>.Popon empty collections,First,Last,Single,Max,MinandAverageon empty sequences,Nullable<T>.Valuewithout a value, and changing a collection during enumeration. - Prefer safe variants.
FirstOrDefault,TryDequeue,TryPop,TryGetValueandHasValuecheck without throwing. - Modifying while enumerating.
List<T>,Dictionary<TKey,TValue>and most collections detect changes through a version number and throw on the nextMoveNext(). Iterate over a copy (list.ToList()) or collect changes and apply them afterwards. - Throw it for state, not arguments. If the same call would succeed with a different argument, it is an argument problem.
- Document the required state. Say in the message what the caller has to do first.
ObjectDisposedExceptionis the more specific choice when the object has been disposed. UseObjectDisposedException.ThrowIf(disposed, this).asynccode: exceptions thrown in anasyncmethod surface when the task is awaited, not at the call.- Do not catch it to cover up a bug. Fix the order of calls instead.