Typecasting Nulls

I discovered something I didn't know about C# recently. Having worked with C# for several years now, it's becoming less common that I run into new things, so I thought I'd share this small bit of knowledge.   Consider the following code snippet, which represents a console application:

   1: public class MyClass {
   2:     public static void Main() {
   3:       MyClass foo;
   5:       foo = null as MyClass;
   6:       Console.WriteLine( "null as MyClass succeeded" );
   8:       foo = new object() as MyClass;
   9:       Console.WriteLine( "new object() as MyClass succeeded" );
  11:       foo = ( MyClass ) null;
  12:       Console.WriteLine( "( MyClass ) null succeeded" );
  14:       foo = ( MyClass ) new object();
  15:       Console.WriteLine( "( MyClass ) new object() succeeded" );
  16:     }
  17: }


 The  application uses the as operator and the type cast operator.  Both are used to convert between compatible reference types.  According to the MSDN documentation, the as operator is like the type cast operator, except it returns null on conversion failure, rather than throwing an exception. 

So I expected lines 5 and 8 to succeed, since the as operator will return null if you try to convert something to an incompatible type.  And I expected line 14 to throw an exception, since the object class does not derive from MyClass. 

It was line 11 that surprised me.  It actually works.  I expected a typecast of a null value to throw an exception, but it just happily returned null.  Since I expected a typecast to throw an exception when the type did not match, I expected this to throw an exception.

As a point of style, even though the typecast of a null works, I believe if you are anticipating that a value may be null, it is better to use the as operator since it is more widely known that it can yield a null.  I'm sure that many C# programmers out there (like me) would not anticipate that a typecast can return a null.

Just for the record, another difference between the as operator and a type cast is that a type cast can perform user defined conversion, while an as does not.  For more explanation of this, along with many other C# topics, I'd recommend that you read Effective C# by Bill Wagner.

0 comments: (+add yours?)