Skip to main content

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.


Post a Comment

Popular posts from this blog

Losing precision after multiplication in SQL Server

Yesterday I was doing a little multiplication operation in SQL SERVER. The computation involves multiplication of two decimal numbers. A point to note here is that I've to be very careful while performing the calculations because it's a monetary thing. So, Whatever the calculation made, it must be very accurate such that I shouldn't miss any fractions as it costs in MILLIONS. The scenario is that I've two numbers, after multiplying each other I'm losing the precision of the values. I've tried to check my database for any faulty data that caused the issue. But the data is absolutely fine.

Stack implementation using C#

A stack is a data structure.

And the definition as on Wikipedia:
In computer science, a stack is an abstract data type that serves as a collection of elements, with two principal operations: push, which adds an element to the collection, and pop, which removes the most recently added element that was not yet removed.
Data structures are so simple if you can understand everything in it. They are just another programs which are tied together with small pieces of implementation.