The exception that is thrown when a method call is invalid for the object's current state.
Assembly: mscorlib (in mscorlib.dll)
Initializes a new instance of theclass.
Initializes a new instance of theclass with serialized data.
Initializes a new instance of theclass with a specified error message.
Initializes a new instance of theclass with a specified error message and a reference to the inner exception that is the cause of this exception.
Gets a collection of key/value pairs that provide additional user-defined information about the exception.(Inherited from Exception.)
Gets or sets a link to the help file associated with this exception.(Inherited from Exception.)
Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.(Inherited from Exception.)
Gets a message that describes the current exception.(Inherited from Exception.)
Gets or sets the name of the application or the object that causes the error.(Inherited from Exception.)
Gets a string representation of the immediate frames on the call stack.(Inherited from Exception.)
Gets the method that throws the current exception.(Inherited from Exception.)
Determines whether the specified object is equal to the current object.(Inherited from Object.)
Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.(Inherited from Object.)
Serves as the default hash function. (Inherited from Object.)
Gets the runtime type of the current instance.(Inherited from Exception.)
Creates and returns a string representation of the current exception.(Inherited from Exception.)
is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments. Typically, it is thrown when the state of an object cannot support the method call. For example, an exception is thrown by methods such as:
ResourceSet.GetString if the resource set is closed before the method call is made.
XContainer.Add, if the object or objects to be added would result in an incorrectly structured XML document.
A method that attempts to manipulate the UI from a thread that is not the main or UI thread.
Because the Message property.exception can be thrown in a wide variety of circumstances, it is important to read the exception message returned by the
In this section:
Some common causes of InvalidOperationException exceptions
Updating a UI thread from a non-UI thread
Changing a collection while iterating it
Sorting an array or collection whose objects cannot be compared
Casting a Nullable<T> that is null to its underlying type
Calling a System.Linq.Enumerable method on an empty collection
Calling Enumerable.Single or Enumerable.SingleOrDefault on a sequence without one element
Dynamic cross-application domain field access
Throwing an InvalidOperationException exception
The following sections show how some common cases in which inexception is thrown in an app. How you handle the issue depends on the specific situation. Most commonly, however, the exception results from developer error, and the exception can be anticipated and avoided.
Often, worker threads are used to perform some background work that involves gathering data to be displayed in an application's user interface. However. most GUI (graphical user interface) application frameworks for the .NET Framework, such as Windows Forms and Windows Presentation Foundation (WPF), let you access GUI objects only from the thread that creates and manages the UI (the Main or UI thread). Anis thrown when you try to access a UI element from a thread other than the UI thread. The text of the exception message is shown in the following table.
The calling thread cannot access this object because a different thread owns it.
The application called an interface that was marshalled for a different thread.
Windows Forms app
Cross-thread operation not valid: Control 'TextBox1' accessed from a thread other than the thread it was created on.
UI frameworks for the .NET Framework implement a dispatcher pattern that includes a method to check whether a call to a member of a UI element is being executed on the UI thread, and other methods to schedule the call on the UI thread:
In WPF apps, call the Dispatcher.CheckAccess method to determine if a method is running on a non-UI thread. It returns true if the method is running on the UI thread and false otherwise. Call one of the overloads of the Dispatcher.Invoke method to schedule the call on the UI thread.
In UWP apps, call the CoreDispatcher.HasThreadAccess method to determine if a method is running on a non-UI thread. Call the CoreDispatcher.RunAsync method to execute a delegate that updates the UI thread. Use the
In Windows Forms apps, use the Control.InvokeRequired property to determine if a method is running on a non-UI thread. Call one of the overloads of the Control.Invoke method to execute a delegate that updates the UI thread.
The following examples illustrate theexception that is thrown when you attempt to update a UI element from a thread other than the thread that created it. Each example requires that you create two controls:
A text box control named textBox1. In a Windows Forms app, you should set its Multiline property to true.
A button control named threadExampleBtn. The example provides a handler, ThreadsExampleBtn_Click, for the button's Click event.
In each case, the threadExampleBtn_Click event handler calls the DoSomeWork method twice. The first call runs synchronously and succeeds. But the second call, because it runs asynchronously on a thread pool thread, attempts to update the UI from a non-UI thread. This results in a exception.
- WPF and UWP apps
The following version of the DoSomeWork method eliminates the exception in a WPF app.
The following version of the DoSomeWork method eliminates the exception in a UWP app.
- Windows Forms apps
The following version of the DoSomeWork method eliminates the exception in a Windows Forms app.
The foreach statement in C# or For Each statement in Visual Basic is used to iterate the members of a collection and to read or modify its individual elements. However, it can't be used to add or remove items from the collection. Doing this throws anexception with a message that is similar to, "Collection was modified; enumeration operation may not execute."
The following example iterates a collection of integers attempts to add the square of each integer to the collection. The example throws an List<'T>.Add method.with the first call to the
You can eliminate the exception in one of two ways, depending on your application logic:
If elements must be added to the collection while iterating it, you can iterate it by index using the for statement instead of foreach or For Each. The following example uses the for statement to add the square of numbers in the collection to the collection.
Note that you must establish the number of iterations before iterating the collection either by using a counter inside the loop that will exit the loop appropraitely, by iterating backward, from Count - 1 to 0, or, as the example does, by assigning the number of elements in the array to a variable and using it to establish the upper bound of the loop. Otherwise, if an element is added to the collection on every iteration, an endless loop results.
If it is not necessary to add elements to the collection while iterating it, you can store the elements to be added in a temporary collection that you add when iterating the collection has finished. The following example uses this approach to add the square of numbers in a collection to a temporary collection, and then to combine the collections into a single array object.
General-purpose sorting methods, such as the Array.Sort(Array) method or the List<'T>.Sort() method, usually require that at least one of the objects to be sorted implement the IComparable<'T> or the IComparable interface. If not, the collection or array cannot be sorted, and the method throws an exception. The following example defines a Person class, stores two Person objects in a generic List<'T> object, and attempts to sort them. As the output from the example shows, the call to the List<'T>.Sort() method throws an .
You can eliminate the exception in any of three ways:
If you can own the type that you are trying to sort (that is, if you control its source code), you can modify it to implement the IComparable<'T> or the IComparable interface. This requires that you implement either the IComparable<'T>.CompareTo or the CompareTo method. Adding an interface implementation to an existing type is not a breaking change.
The following example uses this approach to provide an IComparable<'T> implementation for the Person class. You can still call the collection or array's general sorting method and, as the output from the example shows, the collection sorts successfully.
If you cannot modify the source code for the type you are trying to sort, you can define a special-purpose sorting class that implements the IComparer<'T> interface. You can call an overload of the Sort method that includes an IComparer<'T> parameter. This approach is especially useful if you want to develop a specialized sorting class that can sort objects based on multiple criteria.
The following example uses the approach by developing a custom PersonComparer class that is used to sort Person collections. It then passes an instance of this class to the List<'T>.Sort(IComparer<'T>) method.
If you cannot modify the source code for the type you are trying to sort, you can create a Comparison<'T> delegate to perform the sorting. The delegate signature is
The following example uses the approach by defining a PersonComparison method that matches the Comparison<'T> delegate signature. It then passes this delegate to the List<'T>.Sort(Comparison<'T>) method.
Attempting to cast a Nullable<'T> value that is null to its underlying type throws an exception and displays the error message, "Nullable object must have a value.
The following example throws anexception when it attempts to iterate an array that includes a Nullable(Of Integer) value.
To prevent the exception:
Use the Nullable<'T>.HasValue property to select only those elements that are not null.
Call one of the Nullable<'T>.GetValueOrDefault overloads to provide a default value for a null value.
The following example does both to avoid theexception.
The Enumerable.Aggregate<'TSource>, Enumerable.Average, Enumerable.First<'TSource>, Enumerable.Last<'TSource>, Enumerable.Max, Enumerable.Min, Enumerable.Single<'TSource>, and Enumerable.SingleOrDefault<'TSource> methods perform operations on a sequence and return a single result. Some overloads of these methods throw an exception when the sequence is empty, while other overloads return null. The Enumerable.SingleOrDefault<'TSource> method also throws an exception when the sequence contains more than one element.
Most of the methods that throw anexception are overloads. Be sure that you understand the behavior of the overload that you choose.
The following table lists the exception messages from the System.Linq.Enumerable methods.exception objects thrown by calls to some
Sequence contains no elements
Sequence contains no matching element
Sequence contains more than one matching element
How you eliminate or handle the exception depends on your application's assumptions and on the particular method you call.
When you deliberately call one of these methods without checking for an empty sequence, you are assuming that the sequence is not empty, and that an empty sequence is an unexpected occurrence. In this case, catching or rethrowing the exception is appropriate .
If your failure to check for an empty sequence was inadvertent, you can call one of the overloads of the Enumerable.Any<'TSource> overload to determine whether a sequence contains any elements.
Calling the Enumerable.Any<'TSource>(IEnumerable<'TSource>, Func<'TSource, Boolean>) method before generating a sequence can improve performance if the data to be processed might contain a large number of elements or if operation that generates the sequence is expensive.
If you've called a method such as Enumerable.First<'TSource>, Enumerable.Last<'TSource>, or Enumerable.Single<'TSource>, you can substitute an alternate method, such as Enumerable.FirstOrDefault<'TSource>, Enumerable.LastOrDefault<'TSource>, or Enumerable.SingleOrDefault<'TSource>, that returns a default value instead of a member of the sequence.
The examples provide additional detail.
The following example uses the Enumerable.Average method to compute the average of a sequence whose values are greater than 4. Since no values from the original array exceed 4, no values are included in the sequence, and the method throws an exception.
The exception can be eliminated by calling the Any<'TSource> method to determine whether the sequence contains any elements before calling the method that processes the sequence, as the following example shows.
The Enumerable.First<'TSource> method returns the first item in a sequence or the first element in a sequence that satisfies a specified condition. If the sequence is empty and therefore does not have a first element, it throws an exception.
In the following example, the Enumerable.First<'TSource>(IEnumerable<'TSource>, Func<'TSource, Boolean>) method throws an exception because the dbQueryResults array doesn't contain an element greater than 4.
You can call the Enumerable.FirstOrDefault<'TSource> method instead of Enumerable.First<'TSource> to return a specified or default value. If the method does not find a first element in the sequence, it returns the default value for that data type. The default value is null for a reference type, zero for a numeric data type, and DateTime.MinValue for the DateTime type.
Interpreting the value returned by the Enumerable.FirstOrDefault<'TSource> method is often complicated by the fact that the default value of the type can be a valid value in the sequence. In this case, you an call the Enumerable.Any<'TSource>method to determine whether the sequence has valid members before calling the Enumerable.First<'TSource> method.
The following example calls the Enumerable.FirstOrDefault<'TSource>(IEnumerable<'TSource>, Func<'TSource, Boolean>) method to prevent the exception thrown in the previous example.
The Enumerable.Single<'TSource> method returns the only element of a sequence, or the only element of a sequence that meets a specified condition. If there are no elements in the sequence, or if there is more than one element , the method throws an exception.
You can use the Enumerable.SingleOrDefault<'TSource> method to return a default value instead of throwing an exception when the sequence contains no elements. However, the Enumerable.SingleOrDefault<'TSource> method still throws an exception when the sequence contains more than one element.
Sequence contains no matching element
Sequence contains more than one matching element
In the following example, the call to the Enumerable.Single<'TSource> method throws an exception because the sequence doesn't have an element greater than 4.
The following example attempts to prevent the Enumerable.SingleOrDefault<'TSource> method. However, because this sequence returns multiple elements whose value is greater than 2, it also throws an exception.exception thrown when a sequence is empty by instead calling the
Calling the Enumerable.Single<'TSource> method assumes that either a sequence or the sequence that meets specified criteria contains only one element. Enumerable.SingleOrDefault<'TSource> assumes a sequence with zero or one result, but no more. If this assumption is a deliberate one on your part and these conditions are not met, rethrowing or catching the resulting is appropriate. Otherwise, or if you expect that invalid conditions will occur with some frequency, you should consider using some other Enumerable method, such as FirstOrDefault<'TSource> or Where<'TSource>.
The OpCodes.Ldflda Microsoft intermediate language (MSIL) instruction throws an exception if the object containing the field whose address you are trying to retrieve is not within the application domain in which your code is executing. The address of a field can only be accessed from the application domain in which it resides.
You should throw anexception only when the state of your object for some reason does not support a particular method call. That is, the method call is valid in some circumstances or contexts, but is invalid in others.
Available since 8
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Available since 8.1
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.