InvalidCastException
The InvalidCastException
occurs when an explicit cast is applied. But the type is not in the same path of the type hierarchy. The cast does not succeed.
To avoid InvalidCastException
, it is ideal to avoid casting altogether. Try using List
and Dictionary
instead of older types for this purpose.
This program shows an InvalidCastException
being thrown. This is generated when a statement tries to cast one reference type to another type that is not compatible.
using System.IO; using System.Text; class Program { static void Main() { // Creates a new object instance of type StringBuilder. // ... Then uses implicit cast to object through assignment. // ... Then tries to use explicit cast to StreamReader, but fails. StringBuilder reference1 = new StringBuilder(); object reference2 = reference1; StreamReader reference3 = (StreamReader)reference2; } }Unhandled Exception: System.InvalidCastException: Unable to cast object of type 'System.Text.StringBuilder' to type 'System.IO.StreamReader'. at Program.Main() in ...Program.cs:line 13
The first reference is of type StringBuilder
. Then an object type is assigned to the StringBuilder
reference, providing an implicit conversion to object type.
StreamReader
is explicitly cast to the object reference.System.InvalidCastException
. The 2 types are not compatible.The C# language also defines the "is" and "as" operators, and these operators can be used to perform safe casts. If one of these casts fails, you will not get an exception.
We looked at InvalidCastException
. This exception is raised when you try to cast an object reference to a more derived class
that is not compatible.