1

There definitely has to be a question like this, but I'm unable to find it - perhaps I'm phrasing it wrong. All my searches have led to articles on how to use arrays in C#.

A little background: I'm trying to load many objects into an array. I'm wondering if the array will get the OutOfMemory exception due to too many pointers or the size of the cumulative objects in the array. I know that objects have an innate 2 GB size limit in .NET, but does it stem from the objects themselves in the array?

For example, if I have n objects in the array, does the array have a memory size of n * sizeof(object) or n * sizeof(pointer)?

user3085290
  • 285
  • 1
  • 2
  • 10

3 Answers3

2

If the objects are value types, then it's storing the actual objects in the array and the size of the array is n * the size of the object. If the types are reference types then the array is storing references to the objects elsewhere, and the size of the array is n * the size of a pointer.

Servy
  • 202,030
  • 26
  • 332
  • 449
1

The array simply consists of N slots of the element type. If the element type is a reference type then the array stores references (initially all null). There is no special case for ref vs. value typed elements.

It is logically impossible for the array to hold reference type objects "inline". What if those classes do not have a default constructor? Then you could not instantiate such an array.

usr
  • 168,620
  • 35
  • 240
  • 369
0

If you're worried about the OutOfMemoryException please see the answer here: https://stackoverflow.com/a/1088044/87464

That being said, a single 2GB array of reference types, even on 64bit systems, is a huge amount of objects. Even with 8 byte references, you have the ability to allocate an array of 268,435,456 object references - each of which can be very large (up to 2GB, more if they're using nested objects). That's more memory than would ever really be required by most applications.

A member of the .NET Common Language Runtime team has posted an in-depth blog entry about the memory limitations of arrays http://blogs.msdn.com/b/joshwil/archive/2005/08/10/450202.aspx and using BigArray to get around any size limitations

Community
  • 1
  • 1
nvuono
  • 3,323
  • 26
  • 27