Zac Bowling’s Blog

Human Code Generator

Archive for February 20th, 2006

Casting

with 3 comments

Interesting thought after talking with MDK on #mono tonight. Casting in CLI is a fun quirky mess. When trying to explain it, with implicit casting and explicit casting, the ‘isinst‘ and ‘castclass‘ and the like don’t really help explain it. Neither do the optimizations of the various compilers and each of the casting quirks of each language.

Specifically in C# you have a few options, such as the “as” keyword or the “(…)” operator. If the compiler can’t optimize the code block in some other way or if an implicit/explicit function conversion isn’t specified, the ‘as’ keyword will generate the “isinst” code, where as the “(…)” operator will generate the “castclass” code. The biggest difference from a pure IL perspective (not excluding how C# allows you to get here) is that ‘castclass’ will check the type and throw an InvaildCastException if it can’t cast, where as ‘isinst’ will simply pass back a null if it can’t cast the value for you.

This also explains why you can use a “(…)” operator to cast a value type but why you can’t use the “as” keyword on them. Since the ‘as’ keyword would try to generate the ‘isinst’ code, if the cast failed, it would try to return null, and in .NET, value types can never be null. If you are trying to be proactive to prevent as many exceptions from being thrown as possible (since exceptions are such resource hogs), then it seems better to use the ‘as’ keyword on all your object types and checking to see if they are null after casting, if its necessary. Be careful though. Finding a Null exception is much more difficult then tracking a casting exception when it happens. If its a value type you are trying to convert such as trying to convert from an int to a short maybe, then you might be stuck with some manual checks for things like overflow (like maybe ‘ if( x < Int16.MaxValue ) …; ‘ ) or whatever.

Now I’m wondering how this all changed with 2.0 where you can now have nullable types? Looks like I’m going to be hacking tonight. :-)

Written by zbowling

February 20th, 2006 at 10:25 pm

Posted in Uncategorized

Tagged with