Thursday, August 23, 2007

The surprising behavior of "as" in C#

This article may be extremely obvious to many people, but I am sure a lot of C# developers will be surprised by what will follow.

What's the difference between

MyType myObject1 = (MyType) anotherObject; 

and:

MyType myObject2 = anotherObject as MyType; 

Well, when "anotherObject" is assignable to MyType, both lines of code do the exact same thing, but when "anotherObject" is not of the correct type, the assignment to "myObject1" will throw an exception, but the second line of code will run fine and "myObject2" will be null.

Surprised? I was too, but it's in the C# specs.

FYI, the type cast is compiled to the "castclass" IL instruction, while the "as" version is compiled to the "isinst" instruction. Two different beasts
 

0 comments: