Freigeben über


C++/CLI casts operator illustration

After reading the excellent Cast Notation and Introduction of safe_cast<>, I thought I would try the following:

int main()

{

String ^ s = "string/chaîne/cadena" ;

Object ^ o = s ;

String ^ s1 = safe_cast<String ^>(o) ; // string s1 = (string) o;

// ldloc.0 / castclass string / stloc.3

Console::WriteLine( "{0} ({1})", s1, s1->GetType() ) ;

String ^ s2 = dynamic_cast<String ^>(o) ; // string s2 = o as string;

// ldloc.0 / isinst string / stloc.2

Console::WriteLine( "{0} ({1})", s2, s2->GetType() ) ; // ldloc.0 / stloc.1

o = 3 ; // boxing

String ^ s3 = static_cast<String ^>(o) ; // ldloc.0 / stloc.3

Console::WriteLine( "{0} ({1})", s3, s3->GetType() ) ;

return 0;

}

 

I had to compile with /clr:pure. What do you think the output is?

 

 

 

string/chaîne/cadena (System.String)

string/chaîne/cadena (System.String)

3 (System.Int32)

 

Hmmm…

For even more fun, look at the s3 value in the local or watch window!