InvalidOperationException

When an operation is carried out on an object that’s not in a valid state to do so, this exception type is raised. Sometimes this is due to not following a certain “protocol” that may be documented informally in the documentation for the type. For example, an object might need some kind of Initialize call before any other members can be called. As a concrete example, consider the SqlConnection class from System.Data.SqlClient:

using (SqlConnection conn = new SqlConnection(connString)) {    Console.WriteLine(conn.ServerVersion);}

Here the ServerVersion property getter will throw the discussed exception because the connection hasn’t been opened yet by calling conn.Open().

This exception is ...

Get C# 5.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.