views:

114

answers:

2

This might be a dupe. I did not find enough information on this.

I was discussing memory allocation for collections in .Net. Where is the memory for elements allocated in a collection?

List<int> myList = new List<int>();

The variable myList is allocated on stack and it references the List object created on heap.

The question is when int elements are added to the myList, where would they be created ?

Can anyone point the right direction?

+8  A: 

The elements will be created on the heap. The only thing that lives on the stack is the pointer (reference) to the list (List<> is a reference type)

Philippe Leybaert
+2  A: 

The elements will also reside in the heap (in an array, that's how List works internally).

In principle, only local variables and arguments are be allocated on the stack and everything else goes on the heap (unless you use rare things such as stackalloc, but you don't need to worry about that)

Matti Virkkunen
Would there be an issue of boxing if value types also reside on heap ?
Yogendra
@Yogendra: Yes, a simple value type (think numbers) does need to be boxes before putting it on the heap. An exception are primitive arrays, which do contain value types but still reside on the heap. Elements in primitive arrays are not boxed.
Matti Virkkunen
No, List<int> doesn't box. ArrayList does.
Hans Passant
Yes, as I said, primitive arrays are not boxed and `List<int>` uses an array in the inside.
Matti Virkkunen
Be careful with `List<>`. It's true there's no boxing going on, but it behaves very different compared to an array: http://www.blog.activa.be/2008/05/25/TheProblemsWithValueTypes.aspx
Philippe Leybaert
Correct, but mutable structs are typically problematic anyway.
Lasse V. Karlsen
ArrayList uses an array as well. Avoiding boxing is a prime feature of generics.
Hans Passant