Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Generic lists stored on the stack or the heap in C#?

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?

like image 820
TAdhav Avatar asked Sep 13 '10 16:09

TAdhav


2 Answers

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.

like image 66
Andy Avatar answered Oct 14 '22 16:10

Andy


List<T> is a reference type. Internally it uses T[]. Array 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.

like image 36
Brian Rasmussen Avatar answered Oct 14 '22 17:10

Brian Rasmussen