It's using the IL instruction isinst
to perform the cast instead of the castclass
instruction that is used when casting. This is a special instruction which performs the cast if it is valid, else leaves null
on 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 isinst
instruction and castclass
- the main one being that isinst
does 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:
class A
{
public int Foo;
}
class B
{
public int Foo;
public static explicit operator B(A a)
{
return new B { Foo = a.Foo };
}
}
Then the following will succeed:
var a = new A { Foo = 3 };
var b = (B)a;
Console.WriteLine(b.Foo); // prints 3
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'
var a = new A { Foo = 3 };
var b = a as B;
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.