This documentation is archived and is not being maintained.

How to: Use safe_cast and User-Defined Conversions

The following sample shows that user-defined conversions can be invoked by a safe_cast.

// safe_cast_udc.cpp
// compile with: /clr
using namespace System;
value struct V;

ref struct R {
   int x;
   R() {
      x = 1;

   R(int argx) {
      x = argx;

   static operator R::V^(R^ r);

value struct V {
   int x;
   static operator R^(V& v) {
      Console::WriteLine("in operator R^(V& v)");
      R^ r = gcnew R();
      r->x = v.x;  
      return r;

   V(int argx) {
      x = argx;

   R::operator V^(R^ r) {
      Console::WriteLine("in operator V^(R^ r)");
      return gcnew V(r->x);

int main() {
   bool fReturnVal = false;
   V v(2);
   R^ r = safe_cast<R^>(v);   // should invoke UDC
   V^ v2 = safe_cast<V^>(r);   // should invoke UDC


in operator R^(V& v)
in operator V^(R^ r)