C# InvalidCastExceptionUnderstand InvalidCastException, which occurs when a cast fails.
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.CastsException
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.
Info: Casts that use the type name in parentheses are called explicit casts. Usually this exception indicates a coding error.
Tip: 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
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
Notes, example steps.
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.
And: This causes the runtime to throw an exception of type System.InvalidCastException. The 2 types are not compatible.StreamReader
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.ArrayListHashtable
However: Current versions provide the List and Dictionary types, which do not require casting, thus avoiding the problem.ListDictionary
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.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.