How do castings really work at the CLR level?

When you do upcast or downcast, what really happens behind the scenes? I had the idea that when doing something like:

string myString = "abc";
object myObject = myString;
string myStringBack = (string)myObject;

The listing on the last line will only have the purpose of telling the compiler that we are safe, we are not doing anything wrong. So, I had the idea that the cast code will not be embedded on the code itself. I seem to be wrong:

.maxstack 1
.locals init (
    [0] string myString,
    [1] object myObject,
    [2] string myStringBack)
L_0000: nop 
L_0001: ldstr "abc"
L_0006: stloc.0 
L_0007: ldloc.0 
L_0008: stloc.1 
L_0009: ldloc.1 
L_000a: castclass string
L_000f: stloc.2 
L_0010: ret 

Why does the CLR need something like castclass string?

There are two possible options for downcast:

  • You require castclass something. When you hit a line of code that executes castclass, the CLR tries to throw. But then, what happens if I overshadow a string-style string and try to run the code?
  • castclass. , , ( , - ).

, statamente # 4.0 ?

Upcasting and downcasting between compatible reference types performs reference
conversions: a new reference is created that points to the same object.

? , , .

+3
2

, .

. , ?

try
{
    object x = 123;
    object y = (string)x;
}
catch(InvalidCastException ex)
{ ... }

, , ?

, - .

, , . ; , .

Form, ( , - ).

? , , ? castclass. , castclass.

, castclass ?

. CLR , undefined. , , , , , , .

?

, . , . , , , ; , .

, 12, "" 12, "" 12, , "" 12? , 12 , . "" 12 "" 12? ? . "" , "" , - ? - , .

+11

. , .

object foo = "bar";
string baz = (string)foo;

"foo" baz ( , , ). , "". baz foo , ..

foo = "bim";

baz "bim" (, baz ).

( ) . , , , , .. , .

, , , . ( , ), / , .

+4

Source: https://habr.com/ru/post/1744384/


All Articles