C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
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;
}
}
Output
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
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.
StreamReaderHowever: Current versions provide the List and Dictionary types, which do not require casting, thus avoiding the problem.
ListDictionary