Thursday, May 8, 2014

Resolving an Invalid cast exception in C#

Unable to cast object of type 'xxx.ClassA' to type 'xxx.ClassB'.
Often C# developers get this kind of exception at runtime due to invalid cast operation. There are two ways of casting an object to a different type of object.
Most developers only know one type of casting object which is just by using a pair of parenthesis to cast to its target type. Well let's consider two classes ClassA and ClassB. The object of ClassA is casted to ClassB object. Here is what the old style of casting looks like, which causes exception.
ClassA classA = new ClassA();
ClassB classB = (ClassB)classA; //this throws an InvalidCastException.
If we don't use try..catch blocks during casting, the operation will eventually fails.
Inorder to avoid this kind of exception, we've as keyword in C# that doesn't throw any exception. Here is the modified code that doesn't throw any exception.
ClassA classA = new ClassA();
//The following line will not throw any exception and returns null
//if the cast is invalid
ClassB classB = classA as ClassB; //returns null without raising any exception.
Why this code did not throw any error ?
Because when the object of source type doesn't match the target type, then instead of throwing an error it just retuns null which avoids error from popping up.

Hope it helps.