Format | Assembly Format | Description |
---|---|---|
74 <T> | castclass typeTok |
Cast obj to typeTok. |
…, obj → …, obj2
typeTok is a metadata token (a typeref
, typedef
or typespec
), indicating the desired class. If typeTok is a non-nullable value type or a generic parameter type it is interpreted as "boxed" typeTok. If typeTok is a nullable type, Nullable<T>
, it is interpreted as "boxed" T
.
The castclass
instruction determines if obj (of type O
) is an instance of the type typeTok, termed "casting". If the actual type (not the verifier tracked type) of obj is verifier-assignable-to the type typeTok the cast succeeds and obj (as obj2) is returned unchanged while verification tracks its type as typeTok.
Unlike coercions (§III.1.6) and conversions (§III.3.27), a cast never changes the actual type of an object and preserves object identity (see Partition I).
If the cast fails then an InvalidCastException
is thrown. If obj is null, castclass
succeeds and returns null. This behavior differs semantically from isinst
where if obj is null, isinst
fails and returns null.
System.InvalidCastException
is thrown if obj cannot be cast to typeTok.
System.TypeLoadException
is thrown if typeTok cannot be found. This is typically detected when CIL is converted to native code rather than at runtime.
Correct CIL ensures that typeTok is a valid typeRef
, typeDef
or typeSpec
token, and that obj is always either null or an object reference.
Verification tracks the type of obj2 as typeTok.