c# - How do dynamic and value types work? -
c# - How do dynamic and value types work? -
there little piece of code can not understand:
class programme { static void main(string[] args) { var ts = new teststruct() { = 2 }; object ots = ts; dynamic dts = ots; ts.a = 6; dts.a = 4; console.writeline(dts.gettype()); //type teststruct console.writeline("ts.a =" + ts.a); //6 console.writeline("unboxed ts.a =" + ((teststruct)ots).a); //4 console.writeline("dts.a =" + dts.a); //4 console.readkey(); } } public struct teststruct { public int a; }
dts
, ots
refer same variable on heap, gettype
returns dts
teststruct
. dts
teststruct
stored on heap? or not understand?
tl;dr:
dts
, ots
point same, boxed, re-create of ts
. ts
contains original teststruct
separately.
as may know, boxing , unboxing works this:
a key difference same operations on class types boxing , unboxing copies struct value either or out of boxed instance. thus, next boxing or unboxing operation, changes made unboxed struct not reflected in boxed struct.
so in line:
object ots = ts;
you making re-create of struct
, , becomes reference type. have 2 instances of teststruct
. on, original ts
, , sec one, copy, reference type (boxed teststruct
). hence, after line:
dynamic dts = ots;
the boxed re-create of ts
pointed 2 references: ots
, dts
. fact dts
dynamic
irrelevant here. dynamic
does, deferring type checking until run time, , after this, behaves object
:
the compiler packages info operation, , info later used evaluate operation @ run time. part of process, variables of type dynamic compiled variables of type object. therefore, type dynamic exists @ compile time, not @ run time.
you can observe happening when going step step through code in debugger , inspecting values of ts.gethashcode()
, ots.gethashcode()
, dts.gethashcode()
. actual copying may take place not after modify struct.
c# .net
Comments
Post a Comment