Home
Map
InvalidCastExceptionUnderstand InvalidCastException, which occurs when a cast fails.
C#
This page was last reviewed on Sep 25, 2022.
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.
Cast
Exception
Avoiding casts. To avoid InvalidCastException, it is ideal to avoid casting altogether. Try using List and Dictionary instead of older types for this purpose.
List
Dictionary
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.
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.
Detail Avoiding casting (by using generics or objects) is usually the best. This may help performance and code readability.
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
Notes, example steps. The first reference is of type StringBuilder. 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
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.
is
as
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 25, 2022 (edit).
Home
Changes
© 2007-2024 Sam Allen.