Casting in C#

posted @ Friday, December 16, 2005 3:23 PM

 

Garrett Smith of ThoughtWorks discusses his thoughts on the two different ways of performing casting in C#. Garrett states that he prefers the C-style mechanism of casting as it "crashes early". Here's the distinction, when a cast is performed in C# using the C-style casting syntax such as the following:


SomeObject s = (SomeObject)hashTable[i];

An InvalidCastException will be thrown if the cast fails. So, with defensive programming techniques, we are encouraged to wrap our code in a try/catch block. Garrett then mentions that using the "as" operator to perform casting is problematic due to the fact that no exception is thrown. While this is true, when looking at the documentation for the "as" operator, it is noted that when the type conversion fails, null is returned. So in our particular case, we would want to write it as follows:

SomeObject s = hashTable[i] as SomeObject;
if
(s != null)
{
// continue on...
}
else
{
// decide what to do here.
}

Given this option, we now have the opportunity to control whether or not to create and throw an expensive exception or possibly dispatch control back to our application another way without continuing on with a null object reference. We could even further augment our check by using the β€œis” keyword to check to see if a type conversion will work before making the attempt to cast.