TheDeveloperBlog.com

Home | Contact Us

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

C# InvalidCastException

This C# exception article demonstrates 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.


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