TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# InvalidCastException

Understand InvalidCastException, which occurs when a cast fails.
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.CastsException
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.

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

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.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf