Saturday 15 May 2010

c# - Are Structs always stack allocated or sometimes heap allocated? -



c# - Are Structs always stack allocated or sometimes heap allocated? -

i of impression in c#, struct elements allocated on stack , disappear when returning method in created. happens if place struct-values in list , homecoming that? elements survives. are struct instances allocated on heap?

internal struct stru { public int i; } internal class strutry { public list<stru> get(int max) { var l = new list<stru>(); (int = 0; < max; i++) l.add(new stru {i=i}); homecoming l; } }

code printing 0, 1, 2

[test] public void t() { var ll = new strutry().get(3); foreach (var stru in ll) console.writeline("* "+ stru.i); }

first, read post eric lippert on the stack implementation detail. follow the truth value types. specific question

are struct instances allocated on heap?

yes, allocated on heap. there lots of examples of when allocated on heap. if boxed, or if fields in class, or if elements of array, or if value of variable of value type has been closed over, etc.

but happens if place struct-values in list , homecoming that? elements survives.

you're thinking right way, , 1 of salient points on value type might allocated. see sec post referred on truth value types more details. maintain stack implementation detail in mind. key takeaway don't need concern stuff. should concerned semantic difference between value types , reference types.

c# struct allocation

No comments:

Post a Comment