views:

82

answers:

3

Are Generic lists stored on the stack Or the heap?

example

//List of Ints
List<int> myInts = new List<int>();
myInts.Add(5);
myInts.Add(10);
myInts.Add(20);

Is myInts stored on the stack or the heap? If I add an int to the list, does boxing or unboxing occur?

+5  A: 

There is no concept of "heap" or "stack" when creating objects in C# or .NET. While the list is stored on the heap, that is really an implementation detail of how the CLR manages its memory.

There is no boxing or unboxing going on here. That is the advantage of using the generic List class over the non-generic ArrayList. When a new instance of List<int> is created, it is as if you wrote a class with the sole purpose of managing a list of int. There is not even any casting going on behind the scenes when an int is retrieved from the list.

Andy
It might be an implementation detail, but the language specification does mention that instances of reference types are stored on the heap and value types are not.
Brian Rasmussen
http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx
asawyer
@Brian, but that's only part of the story. Where is a value type field of a reference type object stored? With the object. And the larger point is that it could all change in a hypothetical future version.
Anthony Pegram
@Anthony: I know. I wasn't try to explain how things are stored. I was simply pointing out the the language specification covers this a number of times. Please notice that I didn't say that value types are stored on the stack, but simply that they do not incur heap allocation which is the wording used in the spec.
Brian Rasmussen
A: 

For structs like int, the generic list is getting specialized and therefore no boxing/unboxing is required.

Note that the values themselves are stored in a backing array of the List nevertheless.

Dario
+1  A: 

List<T> is a reference type. Instances of reference types are stored on the heap. Since the list in your example is a List<int> it can only hold ints and no boxing occurs. Boxing occurs if you need to treat a value type as a reference type.

Brian Rasmussen
Hi Brain, can you please explain me how exactly memory allocation takes place for this List<int>? Is it mean that added Ints are value types, so they will be stored on stack and then where referance of myInts will be pointing?
Tanuja
@Tanuja: The list itself and all its contents will be stored on the heap. Your reference will point to the list instance on the heap. Value types are stored on the heap if they are part of a reference type (e.g. an int field of a class) or stored in an array.
Brian Rasmussen