c# - Details on what happens when a struct implements an interface -


i came across stackoverflow question: when use struct?

in it, had answer said bit profound:

in addition, realize when struct implements interface - enumerator - , cast implemented type, struct becomes reference type , moved heap. internal dictionary class, enumerator still value type. however, method calls getenumerator(), reference-type ienumerator returned.

exactly mean?

if had like

struct foo : ifoo  {   public int foobar; }  class bar {   public ifoo biz{get; set;} //assume foo }  ...  var b=new bar(); var f=b.biz; f.foobar=123; //what happen here b.biz.foobar=567; //would overwrite above, or have no effect? b.biz=new foo(); //and here!? 

what detailed semantics of value-type structure being treated reference-type?

every declaration of structure type declares 2 types within runtime: value type, , heap object type. point of view of external code, heap object type behave class fields , methods of corresponding value type. point of view of internal code, heap type behave though has field this of corresponding value type.

attempting cast value type reference type (object, valuetype, enum, or interface type) generate new instance of corresponding heap object type, , return reference new instance. same thing happen if 1 attempts store value type reference-type storage location, or pass reference-type parameter. once value has been converted heap object, behave--from point of view of external code--as heap object.

the situation in value type's implementation of interface may used without value type first being converted heap object when it's passed generic type parameter has interface type constraint. in particular situation, interface members may used on value type instance without having converted heap object first.


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -