C# InvalidCastException

Warning

You want to see an example C# program that causes the InvalidCastException to be raised during runtime. The InvalidCastException occurs when an explicit cast is applied to a type that is not in the same path of the type hierarchy.

This C# exception article demonstrates InvalidCastException.

Example

Note

First, this program is designed to demonstrate an InvalidCastException being thrown by the .NET Framework. An InvalidCastException is generated by the runtime when a statement tries to cast one reference type to a reference type that is not compatible.

Casts that use the type name in ( ) parentheses are called explicit casts. Usually this exception indicates a coding error; it is possible to remedy this by defining a custom explicit cast method, but not usually recommended. Instead, avoiding casting altogether is usually the best.

Program that generates InvalidCastException [C#]

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;
    }
}

Exception generated at runtime

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
Main method

Overview. The program introduces the Main entry point and three variables of different reference types are used. The first reference happens to be of type StringBuilder; this exact type is not important to the point of this article. Then, an object type is assigned to the StringBuilder reference, providing an implicit conversion to object type.

StringBuilder Secrets

Next, a reference of type StreamReader is explicitly casted to the object reference. This causes the runtime to throw an exception of type System.InvalidCastException, indicating that the two types are not compatible. The StringBuilder type cannot be casted to a StreamReader type.

Using StreamReader

Generics. In the first few versions of the .NET Framework, generic types did not exist and you had to cast from the ArrayList and Hashtable types frequently. This caused a performance hit because of the boxing and unboxing conversions. However, current versions of the .NET Framework provide the List and Dictionary types, which do not require any casting, thus avoiding the InvalidCastException problem entirely.

Unboxing TestAs keyword

Using 'is' and 'as'. 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; instead, you will receive the value false or null.

Is Cast Example As Cast Example

Summary

.NET Framework information

We looked at the InvalidCastException type in the .NET Framework and demonstrated its cause in a C# program. This exception is raised when you try to cast an object reference to a more derived class that is not compatible because of a different type hierarchy. You can avoid almost all InvalidCastException instances by using generic types or adding method overloads that do not accept object references.

Exception Handling
.NET