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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.