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.

Comments

Post a Comment

Popular posts from this blog

Losing precision after multiplication in SQL Server

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

Hacker Rank: 2D Array - DS Solution

I've been trying to solve the puzzles on HackerRank.com lately. This post is just to solve the problem in Arrays section of Hacker Rank I feel better to solve the problems though. It certainly improves some area in programming language. As I'm a C# developer the problem is solved using C# as programming language. Question: https://www.hackerrank.com/challenges/2d-array And the solution is