Compartir a través de


safe_cast

safe_cast allows you to change the type of an expression and generate verifiable MSIL code.

[cli]::safe_cast<type-id>(expression)

Parameters

  • type-id
    A handle to a reference or value type, a value type, or a tracking reference to a reference or value type.

  • source
    An expression that evaluates to a handle to a reference or value type, a value type, or a tracking reference to a reference or value type.

Remarks

The expression safe_cast<type-id>(expression) converts the operand expression to an object of type type-id.

The compiler will accept a static_cast in most places that it will accept a safe_cast. However, safe_cast is guaranteed to produce verifiable MSIL, where as a static_cast could produce unverifiable MSIL. See Pure and Verifiable Code and PEVerify Tool (Peverify.exe) for more information on verifiable code.

Like static_cast, safe_cast invokes user-defined conversions.

For more information about casts, see Casting Operators.

safe_cast does not apply a const_cast (cast away const).

safe_cast is in the cli namespace. See cli Namespace for more information.

For more information on safe_cast, see:

Example

One example of where the compiler will not accept a static_cast but will accept a safe_cast is for casts between unrelated interface types. With safe_cast, the compiler will not issue a conversion error and will perform a check at runtime to see if the cast is possible

// safe_cast.cpp
// compile with: /clr
using namespace System;

interface class I1 {};
interface class I2 {};
interface class I3 {};

ref class X : public I1, public I2 {};

int main() {
   I1^ i1 = gcnew X;
   I2^ i2 = safe_cast<I2^>(i1);   // OK, I1 and I2 have common type: X
   // I2^ i3 = static_cast<I2^>(i1);   C2440 use safe_cast instead
   try {
      I3^ i4 = safe_cast<I3^>(i1);   // fail at runtime, no common type
   } 
   catch(InvalidCastException^) {
      Console::WriteLine("Caught expected exception");
   }
}

Caught expected exception

Requirements

Compiler option: /clr

See Also

Concepts

Language Features for Targeting the CLR