TheDeveloperBlog.com


C# InvalidCastException

InvalidCastException. An InvalidCastException has been thrown. 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.

Casts

Example. First, this program shows 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 (by using generics or objects) is usually the best. This may help performance and code readability.

C# program that generates InvalidCastException

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

In this example, the first reference happens to be of type StringBuilder. This exact type is not important. Then an object type is assigned to the StringBuilder reference, providing an implicit conversion to object type.

StringBuilder

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

StreamReader

Generics. In the first few versions of the .NET Framework, generic types did not exist and you had to frequently cast from the ArrayList and Hashtable types. This caused a performance hit because of the boxing and unboxing conversions.

ArrayListHashtableUnboxing Test

However: Current versions provide the List and Dictionary types, which do not require casting, thus avoiding the problem.

ListDictionary

Operators. 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.

IsAs

Summary. We looked at the InvalidCastException type 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.

Tip: You can avoid InvalidCastException instances by using generic types or method overloads that do not accept object references.