2

I understand int's, as are all value types, are stored on the stack. Int's can be boxed into objects which then means the int is storage on the heap. BUT what happens when an int is stored in a List or int[]?

I know List ofT is a class/reference type/heap stored type - does this mean int's in a List are boxed onto the heap?

Thanks

JamesRedcoat
  • 2,083
  • 2
  • 15
  • 13
  • 1
    " are stored on the stack" is incorrect, they may be stored on the stack. http://stackoverflow.com/questions/1932155/why-value-types-are-stored-onto-stacks – Ritch Melton Jul 19 '11 at 21:36
  • Possible duplicate of http://stackoverflow.com/questions/1113819/c-arrays-heap-and-stack-and-value-types – Paolo Moretti Jul 19 '11 at 21:37

3 Answers3

2

No boxing is necessary when working with the generic List<int> type.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

It is not boxed if it is stored in a typed List

http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx

"If a value type is used for type T, the compiler generates an implementation of the List class specifically for that value type. That means a list element of a List object does not have to be boxed before the element can be used, and after about 500 list elements are created the memory saved not boxing list elements is greater than the memory used to generate the class implementation."

Nikki9696
  • 6,260
  • 1
  • 28
  • 23
0

I know List ofT is a class/reference type/heap stored type - does this mean int's in a List are boxed onto the heap?

Placing an int in storage that is allocated on the heap is not the same as boxing that int.

Boxing is when the int is individually placed in its own object wrapper. This doesn't happen in a generic List<int>, but would happen in an ArrayList.

http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx

Merlyn Morgan-Graham
  • 58,163
  • 16
  • 128
  • 183