Skip to content

Latest commit

 

History

History
33 lines (18 loc) · 1.83 KB

iii.4.3-castclass.md

File metadata and controls

33 lines (18 loc) · 1.83 KB

III.4.3 castclass – cast an object to a class

Format Assembly Format Description
74 <T> castclass typeTok Cast obj to typeTok.

Stack Transition:

…, obj → …, obj2

Description:

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.

Exceptions:

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.

Correctness:

Correct CIL ensures that typeTok is a valid typeRef, typeDef or typeSpec token, and that obj is always either null or an object reference.

Verifiability:

Verification tracks the type of obj2 as typeTok.