When using the ‘as’ keyword in C# to make a cast which fails, null gets returned. What’s going on in the background? Is it simply suppressing an exception so I don’t have to write handling code for a failure?
I’m interested in the performance characteristics of it compared to a typical cast wrapped in a try-catch.
Related Questions
No related questions found
It’s using the IL instruction
isinstto perform the cast instead of thecastclassinstruction that is used when casting. This is a special instruction which performs the cast if it is valid, else leavesnullon the stack if it isn’t. So no, it doesn’t just suppress an exception, and is orders of magnitude faster than doing so.Note that there are some differences in behaviour between the
isinstinstruction andcastclass– the main one being thatisinstdoes not take into account user-defined cast operators, it only considers direct inheritance hierarchy, e.g. if you define the following two classes with no inheritance hierarchy but an explicit cast operator:Then the following will succeed:
However the following does not compile, with the error ‘Cannot convert type ‘A’ to ‘B’ via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion’
So if you do have any user-defined casts set up (which are typically a bad idea on reference types, for this reason and others) then you should be aware of this difference.