We all understand the concept of boxing and unboxing in C# but type casting is a bit more complicated and we do have more than one option to accomplish it.
The two options that we have is 1) Have an explicit cast to specific type or 2) Use the as keyword for type casting. Let’s look at each one of those in a little detail in code
I am going to call the type casting without any keyword as standard type casting. Below is a code example of one of the ways of doing it right.
object obj1 = new object(); try { Person person1 = (Person)obj1; Console.WriteLine(person1); } catch(InvalidCastException castException) { Console.WriteLine(castException.Message); }
It is apparent from the code that the object we are trying to cast to typeof Person is not actually a person and hence will be unsuccessful, so we are prepared for it by catching the InvalidCastException. This is exactly the problem when using the standard type casting.
We can avoid getting an exception during type casting by using the as keyword. Below is the code example of one way of doing that
object obj1 = new object(); Person person2 = obj1 as Person; if (person2 != null) { Console.WriteLine(person2); } else { Console.WriteLine("The person was not the original type of the object"); }
As we can see from the code above, we used the as keyword to type cast and since the obj1 was is not of the type Person we will get back null as the result of the cast.
I know. The next question one would ask as to why is better than catching an exception since it is almost the same amount of code?
The answer to that question is performance. It is always expensive to throw an exception because of the additional work that needs to done by the runtime like colleting the stacktrace, increase in memory pressure sue to the page faults, etc
There is one catch while using the as keyword though, the as keyword only works for reference types or nullable types, which is understandable since it either returns the casted object or null and there no option to return null in case of failure for non nullable type (value type), it can’t be used there.
In summary, we should try to use as wherever possible as checking for null is definitely preferred as compared to throwing an exception, however if we must use type casting we should catch the specific InvalidCastException for better performance.
Although there is not much to the source code, regardless it could be found at github
Any questions, suggestion or feedback is always welcome.