System.InvalidOperationException Class

Namespace: System
Assembly: System.Runtime.dll

Summary

Represents errors that occur because a method call is invalid for the object's current state.

Constructors

InvalidOperationException() (Protected)
InvalidOperationException(string message) (Public)
InvalidOperationException(string message, Exception innerException) (Public)

Fields

HResult (int)

Properties

ClassName (string)
Message (string)
InnerException (Exception)
Source (string)
StackTrace (string)
TargetSite (MethodBase)

Methods

ToString ()
GetObjectData (SerializationInfo info, StreamingContext context)

Example

Basic Usage

This example demonstrates how to throw an InvalidOperationException when an operation cannot be performed because the object is not in the correct state.


// Imagine a state machine where a transition is attempted in an invalid state.
public class StateMachine
{
    private enum State { Idle, Running, Stopped }
    private State currentState = State.Idle;

    public void Start()
    {
        if (currentState != State.Idle)
        {
            throw new InvalidOperationException("Cannot start. Machine is not in Idle state.");
        }
        currentState = State.Running;
        Console.WriteLine("Machine started.");
    }

    public void Stop()
    {
        if (currentState != State.Running)
        {
            throw new InvalidOperationException("Cannot stop. Machine is not in Running state.");
        }
        currentState = State.Stopped;
        Console.WriteLine("Machine stopped.");
    }

    public void Process()
    {
        if (currentState != State.Running)
        {
            throw new InvalidOperationException("Cannot process. Machine is not in Running state.");
        }
        Console.WriteLine("Processing data...");
    }
}

// Usage
try
{
    StateMachine sm = new StateMachine();
    sm.Start();
    sm.Process();
    sm.Start(); // This will throw an exception
}
catch (InvalidOperationException ex)
{
    Console.WriteLine($"Error: {ex.Message}");
}