Common Type System—Runtime Type Checking
Runtime Type Checking
The CLR offers a variety of ways to perform dynamic runtime type checks that look for polymorphic
compatibility between an instance and a type. Given an object o and a type T, you can use the castclass
and isint IL instructions to check whether o is of type T or whether its type implements T if it’s
an interface or if its type is a subtype of T, in which case it is safe to treat it as a T. The C# language surfaces
these instructions with casting and its is and as keywords:
object o = /*...*/; string s1 = (string)o; // Casting uses ‘castclass’ string s2 = o as string; // ‘as’ uses ‘isinst’ if (o is string) { // ‘is’ also uses ‘isinst’ // ... }
In this example, the cast uses the castclass instruction to dynamically check if the object instance o is
of type System.String. If it’s not, a CastClassException will be thrown by the runtime. Both the as
and is keywords use isinst. This instruction is much like castclass, but it won’t generate an exception;
it leaves behind a 0 if the type doesn’t pass the type check. In the case of as, this means a null will
result if the instance isn’t the correct type; in the case of is, this same condition results in a false.
|

