Are Generic lists stored on the stack Or the heap?
//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?
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.
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 int
s and no boxing occurs. Boxing occurs if you need to treat a value type as a reference type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With